<?
require_once 'constantesMvial.php';
/*
Functions are all Copyrigth(c) 2006/2007, Haugsdal Webtjenester.
*/
/*
if ($_REQUEST["te"])
	$_SESSION["de"]=1;
	
if (!$_SESSION["de"])
	$set_demo=1; // demo-mode
*/
function gatherStats()
{
	global $stat_tbl,$set_url; 
   	$user = ""; 
	$referer = ""; 
   	$url_ereg = "http://$set_url"; 
   	$page = $_SERVER["SCRIPT_NAME"]; 
   	if (isset($_SESSION["valid_user"])) 
      $user = 1; 
  
    if(isset($_SERVER['HTTP_REFERER'])) 
   	{    
    	if (!ereg("$url_ereg", $_SERVER['HTTP_REFERER'])) 
			$referer = $_SERVER['HTTP_REFERER']; 
	} 
	$page=end(split("/", $page)); 
	
	$page=strToDb($page);
	$user=strToDb($user);
	$referer=strToDb($referer);
	if ($user=="")	
		$user=0;	
	$sql = "insert into $stat_tbl (page,member,referer,visit) values('$page','$user','$referer',now())"; 
	q($sql); 

}

function htmlspecialchars_decode_PHP4($uSTR)
{
 return strtr($uSTR, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES)));
} 

function getParam($aVarName,$aVarAlt)
{
	$lVarName=$_REQUEST[$aVarName];
	if (!Empty($lVarName))
	{	
		if (is_array($lVarName))
		{
			$lReturnArray = array();
			foreach ($lVarName as $key => $value) {
				$value=cleanInput($value);
				$key=cleanInput($key);
				$lReturnArray[$key]=$value;
			}
			return $lReturnArray;
		}
		else 
			return cleanInput($lVarName); // Clean input and return it
		
	}
	else 
		return $aVarAlt;
}

function getParamHtml($aVarName,$aVarAlt)
{
	global $set_htmltags_allowed,$set_htmlattribs_allowed;
	
	// tags array
	$lTagsAllowed = explode(',', $set_htmltags_allowed);
	for ($i = 0; $i < count($lTagsAllowed); $i++) $lTagsAllowed[$i] = trim($lTagsAllowed[$i]);
	// attr array
	$lAttrAllowed = explode(',',$set_htmlattribs_allowed);
	for ($i = 0; $i < count($lAttrAllowed); $i++) $lAttrAllowed[$i] = trim($lAttrAllowed[$i]);
		
	$lVarName=$_REQUEST[$aVarName];
	
	if (!Empty($lVarName))
	{
		if (is_array($lVarName))
		{
			$lReturnArray = array();
			foreach ($lVarName as $key => $value) {
				$value=cleanInputHtml($value,$lTagsAllowed,$lAttrAllowed);
				$key=cleanInputHtml($key,$lTagsAllowed,$lAttrAllowed);
				$lReturnArray[$key]=$value;
			}
			return $lReturnArray;
		}
		else{
			return cleanInputHtml($lVarName,$lTagsAllowed,$lAttrAllowed); // Clean input and return it
		}		
	}
	else 
		return $aVarAlt;
}

function getParamInt($aVarName,$aVarAlt)
{
	$lNum="";
	
	if ($_REQUEST["$aVarName"] !="")
		$lNum=$_REQUEST["$aVarName"];
	elseif ($_REQUEST["$aVarName"]!="")
		$lNum=$_REQUEST["$aVarAlt"];
		
		
		//return preg_replace('/[0-9]+/', '', $lNum);
	//return preg_replace('/^([^.][-0-9.]+[^.-])$/', '', $lNum);
	return round($lNum);
	//return preg_replace('/\D+(\.)+/', '', $lNum);
}

function cleanInput($aValue)
{	
	$lMyFilter=new InputFilter("","",0,0,1);
	$lValue = $lMyFilter->process($aValue);
	$lValue=strip_tags($lValue);
	$lValue=stripslashes($lValue);
	
	
	return $lValue;
}

function cleanInputHtml($aValue,$aHtmlTagsAllowed,$aHtmlAttribsAllowed)
{	
	/*
		1st (tags array):    Optional
		2nd (attr array):    Optional
		3rd (tags method):   0 = remove ALL BUT these tags (default)
                     1 = remove ONLY these tags
		4th (attr method):   0 = remove ALL BUT these attributes (default)
                     1 = remove ONLY these attributes
		5th (xss autostrip): 1 = remove all identified problem tags (default)
                     0 = turn this feature off

	*/
	$lMyFilter=new InputFilter($aHtmlTagsAllowed,$aHtmlAttribsAllowed,0,0,1);
	$lValue = $lMyFilter->process($aValue);
	return $lValue;
}

function strToDb($aStr)
{
	/* Protects data and solves quoting issues */
	$aStr=ereg_replace("\|","",$aStr);
	
	if (get_magic_quotes_gpc()) {
       $aStr = stripslashes($aStr);
   	}
	
	 if (!is_numeric($aStr) || $aStr == '0')
	 {
	 	if (version_compare(phpversion(),"4.3.0", "<"))
	 	 	return mysql_escape_string($aStr);
	 	else 
			return mysql_real_escape_string($aStr);
		
	 }
	else 
		return $aStr;
}

function strEnc($aStr)
{
    /* Use everyplace where data is displayed in html forms */
    $lLangSet="utf-8";
    return htmlentities($aStr,ENT_QUOTES,$lLangSet);
}
/*
function date_diff($tfirst, $tsecond)
{
   $totalsec=$tsecond-$tfirst;
   $days=round(($totalsec/86400));
   $totalsec=$totalsec % 86400;
   $hours=round(($totalsec/3600));
   $totalsec=$totalsec % 3600;
   $minutes=round(($totalsec/60));
   $seconds=$totalsec % 60;
  
   
   $ret["days"]=$days;
   $ret["hours"]=$hours;
   $ret["minutes"]=$minutes;
   $ret["secods"]=$seconds;
   
   return $ret;
} 
*/
function getAllParams($aIgnoreArray)
{
	$aIgnoreArray[]="TrckCookie";
	$aIgnoreArray[]="PHPSESSID";
	$lUrl="";
	
	foreach ($_GET as $key => $value) {
		
		if (!empty($value))
			$value=eregi_replace("script","",strip_tags($value));
		
		if (!empty($key))
			$key=eregi_replace("script","",strip_tags($key));
		
		if (!in_array($key,$aIgnoreArray))
			$lUrl.="&amp;$key=$value";
	}
	
	foreach ($_POST as $key => $value) {
		
		if (!empty($value))
			$value=eregi_replace("script","",strip_tags($value));
		
		if (!empty($key))
			$key=eregi_replace("script","",strip_tags($key));
		
		if (!in_array($key,$aIgnoreArray))
			$lUrl.="&amp;$key=$value";
	}
	
	return $lUrl;
}

function dotString($aText,$aSize)
{	
	if (function_exists('mb_strlen'))
	{
		if (mb_strlen($aText,"utf-8")>$aSize)
			$aText=mb_substr($aText,0,$aSize,"utf-8") . "...";
	}
	else 
		$aText=substr($aText,0,$aSize) . "...";
	
	return $aText;
}
function getRemoteIp()
{
	return getenv("REMOTE_ADDR");	
}
function addDaysToTimeStamp($aAddDays,$aTimestamp)
{
	return mktime(
	date("H",$aTimestamp), 
	date("i",$aTimestamp),
	date("s",$aTimestamp),
	date("m",$aTimestamp),
	date("d",$aTimestamp)+$aAddDays,
	date("Y",$aTimestamp));
}

function subtractDaysFromTimeStamp($aAddDays,$aTimestamp)
{
	return mktime(
	date("H",$aTimestamp), 
	date("i",$aTimestamp),
	date("s",$aTimestamp),
	date("m",$aTimestamp),
	date("d",$aTimestamp)-$aAddDays,
	date("Y",$aTimestamp));
	
	
}

function makeExpireDate($daysToAdd)
{
	return mktime(date("H"), date("i"), date("s"), date("m"), date("d")+$daysToAdd,date("Y"));
}

function makeExpireDateFromTimeStamp($timestamp,$daysToAdd)
{
	return mktime(date("H"), date("i"), date("s"), date("m"), date("d")+$daysToAdd,date("Y"));
}
function getDateAddMonths($aTimeStamp,$aMonths)
{
	return mktime(date("H",$aTimeStamp), date("i",$aTimeStamp), date("s",$aTimeStamp), date("m",$aTimeStamp)+$aMonths, date("d",$aTimeStamp),date("Y",$aTimeStamp));
}
function getDateAddDays($aTimeStamp,$aDays)
{
	return mktime(date("H",$aTimeStamp), date("i",$aTimeStamp), date("s",$aTimeStamp), date("m",$aTimeStamp), date("d",$aTimeStamp)+$aDays,date("Y",$aTimeStamp));
}
function getDateSubstMonths($aTimeStamp,$aMonths)
{
	return mktime(date("H",$aTimeStamp), date("i",$aTimeStamp), date("s",$aTimeStamp), date("m",$aTimeStamp)-$aMonths, date("d",$aTimeStamp),date("Y",$aTimeStamp));
}
function formatDate($aDate)
{
	// aDate should have Ymd format
	global $date_format;
	$year=substr($aDate,0,4);
	$month=substr($aDate,4,2);
	$day=substr($aDate,6,2);
	// Date_format grabbed from settings...
	$date_added_1 = $date_format;
	$date_added_1 = ereg_replace("d", "$day", $date_added_1);
	$date_added_1 = ereg_replace("m", "$month", $date_added_1);
	$date_added_1 = ereg_replace("y", "$year", $date_added_1);
	$ad_date1 = $date_added_1;
	return $ad_date1;
}
function formatDateShort($aTimestamp)
{
	global $set_date_format_short;
	
	if (!empty($aTimestamp))
		return date($set_date_format_short,$aTimestamp);
	else 	
		return "";
}
function formatDateLong($aTimestamp)
{
	global $set_date_format_long;
	
	if (!empty($aTimestamp))
		return date($set_date_format_long,$aTimestamp);
	else 	
		return "";
}
function formatDateClock($aTimestamp)
{
	global $set_date_format;
	if (!empty($aTimestamp))
		return date("H:i",$aTimestamp);
}
function check_valid_user($msg)
// see if somebody is logged in and notify them if not
{
	global $set_outer_color, $set_inner_color;
	
	
	$tplLogin=new TplLoad;
  
	$tplLogin->assign("SET_OUTER_COLOR", $set_outer_color);
	$tplLogin->assign("SET_INNER_COLOR", $set_inner_color);
	$tplLogin->assign("USERNAME", getParam("username",""));
	$tplLogin->assign("PASSWORD", getParam("password",""));
	$tplLogin->assign("MSG", "$msg");
	if (!ereg("member_login.php",$_SERVER['PHP_SELF']))
		$tplLogin->assign("SENDTO", $_SERVER['PHP_SELF'] . "?l=1" . getAllParams(array("redirect_to","username","password","login","submit")));
	if (!isset($_SESSION["valid_user"]))
	{
		$tplLogin->display("login_box.tpl");
		include("footer_inc.php");
		exit;
	}
	
		$fArray["TARGET"] = "";
		
		// User variables
		$fArray["VALID_USER"] = $valid_user;
		$fArray["PASSWORD"] = $password;
		$fArray["USERNAME"] = $username;
		if ($rate_mem_page)
			$fArray["SENDTO"] = "rate_user.php?id=$id";
		elseif ($rate_ad_page)
			$fArray["SENDTO"] = "rate.php?id=$id";
			
			
			
		$fArray["MSG"] = $msg;
	
		
	CheckIfStillValidUser();	
		
		
}
function getHowManyDaysRemains($aFuture,$aToday)
{

	$lDifference=$aFuture-$aToday;
	$lDifference = $lDifference/86400;
	return round($lDifference,0);
}
function getExpireDate ($aFromDate,$aAddDays)
{
	// aFromDate on the format YYmd, like 20040212
	
	$from_year=substr($aFromDate,0,4);
	$from_month=substr($aFromDate,4,2);
	$from_day=substr($aFromDate,6,2);
	
	$expire_date_conv = formatDate(date ("Ymd", mktime (date("H"),date("i"),date("s"),$from_month,$from_day+$aAddDays,$from_year)));  
	return $expire_date_conv;
                
}

function delete_user($user_id)
{
	global $usr_tbl,$ads_tbl,$not_tbl,$set_demo,$sel_tbl;
	$sql_links = "select ad_id from $ads_tbl where ad_owner = $user_id";
	$sql_result = q ($sql_links);
	$ant = mysql_numrows($sql_result); 
	$error = 0;
	
	if ($set_demo==1)
	{	
		echo "<p>System in demo-mode. No delete</p>";
		return false;
	}
	
	
	while ($row = mysql_fetch_array($sql_result)) 
	{
		$ad_id = $row["ad_id"];
		
		if (!delete_ad($ad_id))
			$error = 1;
	}
	
	if (!$error)
	{
		$r = "delete from $not_tbl where notify_user_id=$user_id";
		$sql_r = q($r);       	
		
		$r = "delete from $usr_tbl where user_id=$user_id";
		$sql_r = q($r);       	
		
		q("delete from $sel_tbl where sel_option_user=$user_id");
		
		return true;
	}
	addToHistory(10,$user_id,"","");
  
                                	
}
function delete_ad($aAdNumber)
{		
	global $pic_tbl,$ads_tbl,$fav_tbl,$usr_tbl,$userside,$vid_tbl,$set_demo,$doc_tbl,$sel_tbl;	
	$error = 0;
	$aAdNumber = safeIntNumber($aAdNumber);
	$query_pic = "select id from $pic_tbl where pic_ad_id=$aAdNumber";
	$sql_result_pic = q($query_pic);
	
	if ($set_demo==1)
	{
		echo "<p>System in demo-mode. No delete</p>";
		return false;
	}

	
	while ($row_picture=mysql_fetch_array($sql_result_pic))
		if (!deleteImage($row_picture["id"]))
			$error = 1;	
		
	if (!$error)
	{
		// Delete all extra options
		$r = "delete from mvial_ad_extra_options where mv_ad_id=$aAdNumber";
		$sql_r = q($r);
		
		$r = "delete from $fav_tbl where f_adid=$aAdNumber";
		$sql_r = q($r);
	
		$query_ad = "select ad_owner,ad_cat_id from $ads_tbl where ad_id=$aAdNumber";
		$sql_result = q($query_ad);
		$row =  mysql_fetch_array($sql_result);
		$lAdOwnerId= $row["ad_owner"];	
		// What to do here...
		/*JMR: Cambio el funcionamiento del PayBold
		 * $lSql="select pay_bold from $usr_tbl where user_id="  . $row["ad_owner"] . " limit 1";
		$lRes=q($lSql);
		$lRowFetch=mysql_fetch_array($lRes);
		$lNumPayBold=$lRowFetch["pay_bold"];*/
			
		$sql = "update $usr_tbl set user_num_ads = user_num_ads - 1";
		/*JMR: Cambio el funcionamiento del PayBold
		 * if ($lNumPayBold>0)
			$sql.=",pay_bold=pay_bold+1 ";*/
		$sql.=" where user_id ='" . $row["ad_owner"] . "' AND user_num_ads > 0";
		$sql_r = q($sql);

		categoryCounter($row["ad_cat_id"],2);
		userAdsCounter($row["ad_owner"],2);
		
		// Every single ad_has_picture was deleted, remove ad entry
		$r = "delete from $ads_tbl where ad_id=$aAdNumber";
		$sql_r = q($r);
			
		$res_video=q("select * from $vid_tbl where video_adid=$aAdNumber");
		while ($row_video=mysql_fetch_array($res_video))
		{
			deleteVideo($row_video["video_id"]);
		}
		
		$res_video=q("select * from $doc_tbl where f_adid=$aAdNumber");
		while ($row_video=mysql_fetch_array($res_video))
		{
			deleteDoc($row_video["f_id"]);
		}
		q("delete from $sel_tbl where sel_option_ad=$aAdNumber");
		
		addToHistory(10,"",$aAdNumber,"");
		
		return true;
	}
	return false;
}
function setImageSize($aImage,$aMax,$aLayoutImages) 
{ 
	global $set_path;
	if (!$aLayoutImages){		
		if ( file_exists($set_path . "/images/$aImage") && is_readable($set_path . "/images/$aImage") )
  			list($w, $h) = @getimagesize($set_path . "/images/$aImage");
  		else
			logMsg("IMAGEN NO ENCONTRADA","La siguiente imagen se pidió y no existia:".$set_path . "/images/$aImage");
	}else{ 
		if ( file_exists($set_path . "/layout_images/pay_vendors/$aImage") && is_readable($set_path . "/layout_images/pay_vendors/$aImage") )
			list($w, $h) = @getimagesize($set_path . "/layout_images/pay_vendors/$aImage");
		else
			logMsg("IMAGEN NO ENCONTRADA","La siguiente imagen se pidió y no existia:".$set_path . "/images/$aImage");
	}
	
	$size=$aMax;
	if (!$aMax) {
		$size = 100;
	}
	
	if($w > $size || $h > $size) { 
	
	if($w > $h) { 
	$i = $w - $size; 
	$imgSizeArray[0] = round($size); 
	$imgSizeArray[1] = round($h - ($h * ($i / $w))); 
	
	} else { 
	
	$i = $h - $size; 
	$imgSizeArray[0] = round($w - ($w * ($i / $h))); 
	$imgSizeArray[1] = round($size); 
	} 
	
	} else { 
	
	$imgSizeArray[0] = round($w); 
	$imgSizeArray[1] = round($h); 
	} 
	return $imgSizeArray; 
} 

function getManualSize($aSize)
{
	global $set_image_size_large,$set_image_size_small,$set_image_size_thumb;
	
	if ($aSize=="thumb")
	{
		$lSizeArr=split("x",$set_image_size_thumb);
		return $lSizeArr[0];
	}
	elseif ($aSize=="small")
	{
		$lSizeArr=split("x",$set_image_size_small);
		return $lSizeArr[0];
	}
	elseif ($aSize=="large")
	{
		$lSizeArr=split("x",$set_image_size_large);
		return $lSizeArr[0];
	}
}

function safeString($aString)
{
	$aString = htmlspecialchars($aString);
	return $aString;
}
function writeLinkedTitle($aCatid,$aAdID=null)
{
	global $cat_tbl,$ads_tbl,$set_sitename,$lCatArray;
	$lCatId = $aCatid;
	
	if (!$aCatid && $aAdID)
	{
		$lSql="select ad_cat_id from $ads_tbl where ad_id='$aAdID'";
		$lRes=q($lSql);
		$lRowFetch=mysql_fetch_array($lRes);
		$lCatId=$lRowFetch["ad_cat_id"];
	}
	
	if (!isset($home)) 	{
		$home = "";	
	}
	
	$lStr.="<a href='index.php'><img src='layout_images/pointer.gif' border='0' hspace='2' alt='$home' />$home</a>";
//    $lStr.="<a href='index.php'><u>$set_sitename</u></a>  ";
    $lStr.="<a href='index.php'><u>Inicio</u></a>  ";
 	
 	if ($lCatId>0)
 	{
 		$next_id=$lCatId;
 		while ($next_id<>-1)
 		{
 			$next_id=getParent($next_id);
 			$counter++;
 		}
 		$lCat=array_reverse($lCatArray);
 		foreach ($lCat as $cat) {
 			$lStr.=$cat;
 		}
    }
    
    return $lStr;
}
function categoryCounter($aCat,$aDirection)
{
	global $cat_tbl;
	$next_id=$aCat;

	while ($next_id<>-1)
 	{
 		
 		if ($aDirection==1)
			q("update $cat_tbl set cat_total=cat_total+1 where cat_id=$next_id");
		if ($aDirection==2)
			q("update $cat_tbl set cat_total=cat_total-1 where cat_id=$next_id AND cat_total>0");
		$next_id=getParent($next_id);
		$counter++;
 	}
}
function userAdsCounter($aUserID,$aDirection)
{
	global $usr_tbl;
	
	if ($aDirection==1)
		q("update $usr_tbl set user_num_ads=user_num_ads+1 where user_id=$aUserID");
	if ($aDirection==2)
		q("update $usr_tbl set user_num_ads=user_num_ads-1 where user_id=$aUserID AND user_num_ads>0");
}
function addToHistory($aWhat,$aUser,$aAd,$aHistMsg)
{
	global $hist_tbl,$set_log_history,$set_log_history_size;
	//  aWhat	1=Login,2=Contact Person,3=Reset Password,4=Tell a friend,5=Register,6=New ad,7=Update ad,8=Rate Ad,9=Rate User,10=Delete ad
	// 11=Member Notify,12=Member Update Personal,13=Failed Login,14=Resend Password,15=Change Password,16=Footer generation,17=Rss
	
	$aWhat=strToDb($aWhat);
	$aUser=strToDb($aUser);
	$aAd=strToDb($aAd);
	$aHistMsg=strToDb($aHistMsg);
	
	if ($set_log_history)
	{
		$sql_count="select hist_id from $hist_tbl order by hist_id desc limit $set_log_history_size";
		$r=q($sql_count);
		$i=0;
		$lLowest=0;
		while ($row=mysql_fetch_array($r))
		{
			if ($i==0)
				$lLowest=$row["hist_id"];
			else 
				if ($row["hist_id"]<$lLowest)
					$lLowest=$row["hist_id"];
			
			$i++;
			
		}
		q("delete from $hist_tbl where hist_id < $lLowest");
		
		if (!$aUser)
			$aUser=0;
		if (!$aAd)
			$aAd=0;
		
		$sql="insert into $hist_tbl";
		$sql.="(hist_when,hist_what,hist_user,hist_ad,hist_ip,hist_msg) values ";
		$sql.=" (";
		$sql.=time() . ",";
		$sql.=$aWhat . ",";
		$sql.=$aUser . ",";
		$sql.=$aAd . ",";
		$sql.="'" . strToDb(getRemoteIp()) . "',";
		$sql.="'" . $aHistMsg . "'";
		$sql.=")";
		
		$res=q($sql);
		
	}
	return true;
}
function getParent($aId)
{
	global $cat_tbl;
	global $lCatArray;
	global $set_rewrite;
	global $set_multilang_cat,$language;
	$lCatId=$aId;
	
	$sql="select cat_fatherid,cat_name";
	if ($set_multilang_cat)
	{
		$lLangSupportedArray=split(",",$set_multilang_cat);
		foreach ($lLangSupportedArray as $lItem)
			$sql.=",lang_" . $lItem;
	}
	$sql.=" from $cat_tbl where cat_id=$aId";
	$res=q($sql);
	$row=mysql_fetch_array($res);
	$lCatFatherId=$row["cat_fatherid"];
	$lCatName="";
	// Check if user selected category exists
	if (!empty($_SESSION["la"]) AND $set_multilang_cat)
	{
  		$lang_cat = "lang_" . $_SESSION["la"];
  		if (!empty($row["$lang_cat"]))
  			$lCatName = strEnc($row["$lang_cat"]);
	}
  	
	// User has not set any prefered language..
	if (!$lCatName)	
	{
		$lang_cat="lang_" . $language;
		if (!empty($row["$lang_cat"]))
  			$lCatName = strEnc($row["$lang_cat"]); // Get default language, admin choise
  		else 
  			$lCatName = strEnc($row["cat_name"]); // Last resort, use original name..
	}
  	
	if ($set_rewrite)
		$lCatArray[]=" / <a href='".linkCat($lCatId)."'><u>$lCatName</u></a>";
	else 
		$lCatArray[]=" / <a href='index.php?catid=$lCatId'><u>$lCatName</u></a>";
	
	if ($lCatFatherId==0)
		return -1;
	
	return $lCatFatherId;
}
function getCategoryId($ad_id)
{
	global $ads_tbl;
	$ad_id = safeIntNumber($ad_id);
	$sql_cat = "select ad_cat_id from $ads_tbl where ad_id = $ad_id limit 1";
	$result = mysql_query ($sql_cat);
	$row = mysql_fetch_array($result);
	$category_id = $row["ad_cat_id"];
	return $category_id;
	
}

function failMsg($aTitle,$aContent)
{
	
	global $set_webmaster_address,$set_path;
	
	echo "<p><b><font color=red>Error occurred</font></b><br>
	We are sorry, but an unexpected error occurred and the system could not continue serving you. Please contact the webmaster at this site 
	<a href='mailto:$set_webmaster_address'><u>$set_webmaster_address</u></a> and report the problem, along with the error message
	printed below. Please include any other information which may be useful to the webmaster. 
	</p>";
	
	echo "<p>For webmaster: This error with far more details has been logged in PHP Classifieds's error log</p>";
	
	if (ereg("admin",$_SERVER["SCRIPT_NAME"]))
		$lLogFile="config/logs/error.log";
	else 
		$lLogFile="admin/config/logs/error.log";
	
	$aTitle=strtoupper($aTitle);
	$fp = fopen("$lLogFile","a+"); 
	if (!$fp)
		echo "<p><b><font color=red>In addition, the following error occured</font></b><br />Logfile is not writeable! No errors will be logged.</p>";
	else {
		fwrite($fp,"::--------------- ".date("Y.m.d H:i") . " -------------------------------\n$aTitle\n$aContent\nPage: ". cleanInput($_SERVER["SCRIPT_NAME"])."\n\n\n");
		fclose($fp);
	}
	@chmod($lLogFile,0755);
	$show_bar = 0;
}

function logMsg($aTitle,$aContent)
{
	
	global $set_webmaster_address,$set_path;
	
	if (ereg("admin",$_SERVER["SCRIPT_NAME"]))
		$lLogFile="config/logs/error.log";
	else 
		$lLogFile="admin/config/logs/error.log";
	
	$aTitle=strtoupper($aTitle);
	$fp = fopen("$lLogFile","a+"); 
	if (!$fp)
		echo "<p><b><font color=red>In addition, the following error occured</font></b><br />Logfile is not writeable! No errors will be logged.</p>";
	else {
		fwrite($fp,"DEBUG ::--------------- ".date("Y.m.d H:i") . " -------------------------------\n$aTitle\n$aContent\nPage: ". cleanInput($_SERVER["SCRIPT_NAME"])."\n\n\n");
		fclose($fp);
	}
	@chmod($lLogFile,0755);
	$show_bar = 0;
}

function q($aSQL)
{
	global $set_debug_sql;
	if ($set_debug_sql)
	{
		
		if (ereg("admin",$_SERVER["SCRIPT_NAME"]))
			$lLogFile="config/logs/sql.log";
		else 
			$lLogFile="admin/config/logs/sql.log";
		
		if (!ereg("select cat_id,cat_name,cat_total,cat_allow_ads from","$aSQL"))
		{
			$fp = fopen($lLogFile,"a+"); 
			fwrite($fp, "\n\n" . date("Y.m.d H:i") . ":\n$aSQL\n----------\n\n");
			fclose($fp);
		}
	}
	$res = mysql_query($aSQL) or die(failMsg("Invalid MySql query", mysql_error() ."\n\nQuery: $aSQL"));
	return $res;	
}

function specialq($aSQL)
{
	global $set_debug_sql,$set_mysql_host,$set_mysql_base,$set_mysql_host,$set_mysql_pass,$set_mysql_user;
	if ($set_debug_sql)
	{
		
		if (!ereg("select cat_id,cat_name,cat_total,cat_allow_ads from","$aSQL"))
		{
			$fp = fopen("images/sql_log.txt","w+"); 
			fwrite($fp, "\n\n" . date("Y.m.d H:i") . ":\n$aSQL");
			fclose($fp);
		}
	}
	if ($set_debug)
		echo "<br>DEBUG: " . $aSQL . "<br>";
		
	if (!@mysql_connect("$set_mysql_host", "$set_mysql_user", "$set_mysql_pass") OR !@mysql_select_db("$set_mysql_base"))
		echo "ERROR ";
	
	$res = mysql_query($aSQL) or die(failMsg("Invalid MySql query", mysql_error()));
	return $res;	
}

function safeIntNumber($aNumber)
{
	$lNumber = $aNumber;
	settype($lNumber,"integer");
	
	if (is_int($lNumber)) {
		return $lNumber;
	}
	else {
		die(failMsg("Integer problem" , "Ad number provided is not integer."));
	}
}

function validEmail($aEmail)
{
	$aEmail=ereg_replace("_","",$aEmail);	
	if(eregi("^[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,4}$",$aEmail, $regs))
  		return true;
	else
		return false;
}


function unhtmlentities($string)
{
    // replace numeric entities
    $string = preg_replace('~&#x([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $string);
    $string = preg_replace('~&#([0-9]+);~e', 'chr("\\1")', $string);
    // replace literal entities
    $trans_tbl = get_html_translation_table(HTML_ENTITIES);
    $trans_tbl = array_flip($trans_tbl);
    return strtr($string, $trans_tbl);
}


function sendEmail($aTo, $aFrom, $aSubject, $aBody, $aFile="",$aIsHTML=false, $usingCCO = false)
{
	global $set_path,$set_path,$set_inbuilt_php_force,$set_sitename;
	global $set_smtp_host,$set_smtp_user,$set_smtp_pass,$set_webmaster_email;
	
	if(SEND_EMAILS==0 && DEBUG_EMAIL==0) return true;
	
	/**
	 * JMR: Cuando DEBUG_EMAIL se setea en 1 todos los mails serán enviados a una casilla de prueba especificada en la constante: DEBUG_EMAIL_ADDRESS 
	 * */
	if(DEBUG_EMAIL == 1){
		$aTo = DEBUG_EMAIL_ADDRESS;
	}
	
	if (!$aIsHTML)
	{
		//$aSubject=html_entity_decode_utf8($aSubject);
		//$aBody=html_entity_decode_utf8($aBody);
		$aSubject=unhtmlentities($aSubject);
		$aBody=unhtmlentities($aBody);
		
		//$aSubject = str_replace("&amp;", "&", str_replace("\0", "", htmlentities(html_entity_decode(htmlentities($aSubject, ENT_COMPAT, 'UTF-8'))))); 
		//$aBody = str_replace("&amp;", "&", str_replace("\0", "", htmlentities(html_entity_decode(htmlentities($aBody, ENT_COMPAT, 'UTF-8'))))); 
		
		$aSubject=stripcslashes($aSubject);
		$aBody=stripcslashes($aBody);
		$aFrom=stripcslashes($aFrom);
	}
	if (!$aFrom) 	{ 	die(failMsg("No sender (Code #100)","No sender is specified."));			}
	if (!$aTo) 		{ 	die(failMsg("No reciept (Code #101)","No recipient is specified."));	}
	if (!$aSubject) { die(failMsg("No subject (Code #102)","No subject is specified."));		}
	if (!$aBody) 	{ 	die(failMsg("No body (Code #103)","Nobody is specified."));				}

	if (!$aIsHTML)
	{
		$aBody = ereg_replace("<br>","\r\n",$aBody);
		$aBody = ereg_replace("<br/>","\r\n",$aBody);
		$aBody = ereg_replace("<br />","\r\n",$aBody);
	}
	$headers = "From: $aFrom\r\n";
	
	if ($set_inbuilt_php_force=="1") // Old style PHP Mailer
	{	
		@ini_set(sendmail_from, $aFrom);
		$aHeader = "Return-Path: $aFrom\n";
		$aHeader .= "X-Sender: $aFrom\n";
		$aHeader .= "From: $set_sitename <$aFrom>\n";
		$aHeader .= "X-Mailer:PHP 5.1\n";
		$aHeader .= "MIME-Version: 1.0\n";		
		mail($aTo,$aSubject,$aBody,$aHeader);
		return true;
	}
	else // New style Mailer
	{
		$mail = new PHPMailer();
		$mail->Subject=$aSubject;
		//JMR: Agregue esta linea por que el newsletter se enviaba con caracteres \ y se veia mal
		if($aIsHTML){
			$aBody =  str_replace("\\", "", $aBody);
			
		}		
		$mail->Body=$aBody;
		$mail->FromName=$set_sitename;
		$mail->From=$aFrom;
		$mail->AddReplyTo($aFrom);
		if($usingCCO === false){
			$mail->AddAddress($aTo);
		}else
			$mail->AddBCC($aTo); //JMR: Iadd this line
		$mail->WordWrap = 70;  
		$mail->IsHTML($aIsHTML);  
		$mail->CharSet="utf-8"; 
		
		if ($aFile!="")   
			$mail->AddAttachment($aFile);
		$mail->PluginDir = "$set_path/tools/phpmailer/";

		if (!empty($set_smtp_host))
		{
			$mail->IsSMTP();                                      // set mailer to use SMTP
			$mail->Host = $set_smtp_host;  // specify main and backup server
			if ($set_smtp_user!="")
			{
				$mail->SMTPAuth = true;     // turn on SMTP authentication
				$mail->Username = $set_smtp_user;  // SMTP username
				$mail->Password = $set_smtp_pass; // SMTP password
			}
			else 
				$mail->SMTPAuth = false;     // turn on SMTP aut
			
			if(!$mail->Send())
			{
			   echo "Message could not be sent. <p>";
			   echo "Mailer Error: " . $mail->ErrorInfo;
			   exit;
			}
				
					
		
		}
		else 
		{
			if(!$mail->Send())
			{
			   echo "Message could not be sent. <p>";
			   echo "Mailer Error: " . $mail->ErrorInfo;
			   exit;
			}
		}
	
		return true;	
	}

}

function checkReferers($aArray)
{
	// array for allowed domains (lower case please)
	//$referers = array('php.net', 'www.php.net', 'us2.php.net');

	// add upper case referrers
	$size = sizeof($referers);
	for($i = 0; $i < $size; $i++)
	{
  		$referers[] = strtoupper($referers[$i]);
	}
	// check referers
	for($i = 0; $i < sizeof($referers); $i++){
  	if(substr($HTTP_SERVER_VARS['HTTP_REFERER'], 7, strlen($referers[$i])) == $referers[$i]){
   	$bad_referer = FALSE;
   	break;
  	}
  	else
  	{
   		$bad_referer = TRUE;
  	}
	}
	if($bad_referer)
	{
  		header('Location: http://php.net/badreferer.php');
  		exit;
	}
}




function getOneImage($aAdnumber,$aImagenumber,$aFilename,$aLargest)
{
	// Function returns small image to have on the frontpage
	global $pic_tbl;
	
	if ($aImagenumber<>"")
		$sql_ad_has_picture = "select filename from $pic_tbl where id=$aImagenumber";
	elseif ($aAdnumber)	
		$sql_ad_has_picture = "select filename from $pic_tbl where pic_ad_id=$aAdnumber AND main=1 order by id desc limit 1";
  	elseif ($aFilename)	
		$sql_ad_has_picture = "select filename from $pic_tbl where filename=$aAdnumber order by id desc limit 1";
		
	$res = q($sql_ad_has_picture);
	$row = mysql_fetch_array($res);
	
	$filename = $row["filename"];
	
	if ($aLargest)
		$filename=eregi_replace("_tmb1","",$filename);
	return $filename;
}

function formatString($aString,$aValues)
{
	// Example: formatString("Tallet ditt er %1%, tallet mitt er %2%", array("321","3928"));
	for ($i=0;$i<count($aValues);$i++)
	{
		$infront = $i+1;
		$aString = ereg_replace("%$infront%", $aValues[$i],$aString);
	}
	return $aString;
}

function generatePassword($len)
{
		$al = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
		$date = date("Hs");
		$password = "$date";
				
		for ($index = 1; $index <= $len; $index++) 
		{
   			$randomNumber = rand(1,strlen($al));
   			$password .= substr($al,$randomNumber-1,1);
		}
		
		return $password;
			
}

function getErrorMsg($aID)
{
	if ($aID==1)
		return LA_UP_ER1;
	elseif ($aID==2)
		return LA_UP_ER2;
	elseif ($aID==3)
		return LA_UP_ER3;
	elseif ($aID==4)
		return LA_UP_ER4;
	elseif ($aID==5)
		return LA_UP_ER5;
	elseif ($aID==6)
		return LA_UP_ER6;
	else 
		return LA_UP_UNKNOWN;
	
}

function getErrorMsgVideo($aID)
{
	if ($aID==1)
		return LA_UP_ER1_VIDEO;
	elseif ($aID==2)
		return LA_UP_ER2;
	elseif ($aID==3)
		return LA_UP_ER3;
	elseif ($aID==4)
		return LA_UP_ER4;
	elseif ($aID==5)
		return LA_UP_ER5;
	elseif ($aID==6)
		return LA_UP_ER6;
	else 
		return LA_UP_UNKNOWN;
	
}

function uploadImage($aFileArray,$aSaveAs,$aMax,$aDimensionArray,$aVideo,$aProgram,$aNoDate=null)
{
	global $set_chmod,$set_image_filetypes,$set_video_filetypes,$set_doc_filetypes;
	
	if ($set_video_filetypes)
		$lVideoArray=split(",",$set_video_filetypes);
	if ($set_doc_filetypes)
		$lDocArray=split(",",$set_doc_filetypes);
	if ($set_image_filetypes)
		$lImageArray=split(",",$set_image_filetypes);

	
	/*
	Example:
	$FileArray=$_FILES["userfile"];
	$SaveAs="/home/delta/public_html/imageupload/upload/test";
	$MaxSize="10000";
	$DimensionArray[]="200x190";
	$DimensionArray[]="500x500";
	
	$returnValue=uploadImage($FileArray,$SaveAs,$MaxSize,$DimensionArray,"",0);

	if (is_int($returnValue))
		echo getErrorMsg($returnValue);
	else 
	{
		foreach ($returnValue as $item)
		{
			echo "Filen $item ble lastet opp!";
			echo "<img src='upload/$item'><br>";
		}
	}
	
	*/
	// File type check

	if ($aVideo=="1" && !in_array($aFileArray["type"],$lVideoArray))
	{
		echo $aFileArray["type"];
		return 1;
	}
	else if ($aVideo=="2" && !in_array($aFileArray["type"],$lDocArray))
	{
		echo $aFileArray["type"];
		return 1;
	}
	else if (!$aVideo && !in_array($aFileArray["type"],$lImageArray))
	{
		return 1;
	}
		
	// Security check
	if (!is_uploaded_file($aFileArray["tmp_name"]))
		return 2;
	
	// File-size check
	if ($aFileArray["size"]>($aMax*1024))
		return 3;
	
	// New filename
	if (!$aVideo)
	{
		$fileNameSplit=split("/",$aSaveAs);
		$lastFileName=end($fileNameSplit);
		$lToday=date("YmHs");
		if ($aNoDate==1)
			$fileName=$lastFileName;
		else
			$fileName=$lastFileName . "_" . $lToday;
		$dotpos = strrpos($fileName, '.');
		$fileName = str_replace('.', '_', substr($fileName, 0, $dotpos)) . substr($fileName, $dotpos);
		
		
		if ($aFileArray["type"]=="image/gif")
			$ext="gif";
		elseif ($aFileArray["type"]=="image/pjpeg" || $aFileArray["type"]=="image/jpeg")
			$ext="jpg";
		elseif ($aFileArray["type"]=="image/png")
			$ext="png";
		elseif (!$aVideo)
			return 4;
		
		$newFileName=$fileName . "." . $ext;
		if ($aNoDate==1)
			$saveTo_org=$aSaveAs . "." . $ext;
		else 	
			$saveTo_org=$aSaveAs . "_" . $lToday . "." . $ext;
		
	}
	else 
	{
		$fileNameSplit=split("/",$aSaveAs);
		$lastFileName=end($fileNameSplit); // 1 or 2 or 3.. whatever the ad number is
		$newFileName=strtolower($aFileArray["name"]);
		$dotpos = strrpos($newFileName, '.');
		$newFileName = str_replace('.', '_', substr($newFileName, 0, $dotpos)) . substr($newFileName, $dotpos);
		$saveTo_org=$aSaveAs . "_" .$newFileName;
		$newFileName = $lastFileName."_".$newFileName;
	}
	
	
	 if (!@move_uploaded_file($aFileArray['tmp_name'],$saveTo_org))
	 	return 5;
	 	
	 // Do thumb/resize-creation
	$returnFileArray[]=$newFileName;
	 if (!empty($aDimensionArray) && $aProgram!=0)
	 {
	 	$total_dimentions=count($aDimensionArray);
	 
	 	foreach ($aDimensionArray as $item) 
	 	{
	 		
	 		$c++;
	 		$xyArray=split("x",$item);
	 		$x=$xyArray[0];
	 		$y=$xyArray[1];
	 		
	 		$saveTo=$aSaveAs . "_" . $lToday . "_tmb" . $c . "." . $ext;
	 		if ($total_dimentions==$c)
	 			$saveTo=$saveTo_org;
			else{
				$returnFileArray[]=$fileName . "_tmb" . $c . "." . $ext;
				
				if ($aProgram==1)
					makeIMThumb($saveTo_org,$saveTo,$item);
				elseif ($aProgram==2)	
					$res=makeGDThumb($saveTo_org,$saveTo,$ext,$x,$y);
			}
						
			@chmod("$saveTo", octdec($set_chmod)); 	
					
			if (!file_exists($saveTo))
				return 6;
				
					
	 	}
	 	 
	 }
	 
	 return $returnFileArray;	
	     
}

function makeIMThumb($aFromfile,$aToFile,$aGeo)
{
	global $set_magic_path;
	$command = "$set_magic_path -quality 80 -geometry $aGeo $aFromfile $aToFile";
	$res = exec($command);	
}

function makeGDThumb($aInputPath,$aOutputPath,$aFileType,$max_x,$max_y)
{
	
	if ($aFileType=="jpg") 
		$source = ImageCreateFromJPEG ($aInputPath);
	elseif ($aFileType=="png") 
		$source = ImageCreateFromPNG ($aInputPath);
	elseif ($aFileType=="gif") 
		$source = ImageCreateFromGIF ($aInputPath);
	
	list($x, $y) = getimagesize($aInputPath);

	if (($max_x/$max_y) < ($x/$y)) {
	   $save = imagecreatetruecolor($x/($x/$max_x), $y/($x/$max_x));
	}
	else {
	   $save = imagecreatetruecolor($x/($y/$max_y), $y/($y/$max_y));
	}	
	
	imagecopyresampled ($save, $source, 0, 0, 0, 0, imagesx($save), imagesy($save), $x, $y);

	if ($aFileType=="jpg") 
		imagejpeg($save,$aOutputPath,90);
	elseif ($aFileType=="png") 
		imagePNG($save,$aOutputPath);
	elseif ($aFileType=="gif") 
		imageGIF($save,$aOutputPath);		
	
}
function deleteVideo($aVideoId)
{
	global $vid_tbl,$ads_tbl,$set_path,$force,$set_demo;
	
	if ($set_demo==1)
	{	
		echo "<p>System in demo-mode. No delete</p>";
		return false;
	}

	
	if ($aVideoId)
	{
		$sql="select * from $vid_tbl where video_id=$aVideoId";
		$res=q($sql);
		$row=mysql_fetch_array($res);
		$video_id = $row["video_id"];
		$main_file=$row["video_file"];
		
		
		if (file_exists("$set_path/images/videos/$main_file")) { 
			$delete_result = @unlink("$set_path/images/videos/$main_file"); 
		}
		
		$sql = "delete from $vid_tbl where video_id = $aVideoId";
		$r = q($sql);
	}
	return true;
	
}

function deleteDoc($aDocId)
{
	global $doc_tbl,$ads_tbl,$set_path,$force,$set_demo;
	
	if ($set_demo==1)
	{	
		echo "<p>System in demo-mode. No delete</p>";
		return false;
	}

	
	if ($aDocId)
	{
		$sql="select * from $doc_tbl where f_id=$aDocId";
		$res=q($sql);
		$row=mysql_fetch_array($res);
		$f_id = $row["f_id"];
		$main_file=$row["f_file"];
		
		
		if (file_exists("$set_path/images/docs/$main_file")) { 
			$delete_result = @unlink("$set_path/images/docs/$main_file"); 
		}
		
		$sql = "delete from $doc_tbl where f_id = $aDocId";
		$r = q($sql);
	}
	return true;
	
}



function deleteImage($aImgId)
{
	global $pic_tbl,$ads_tbl,$set_path,$force,$set_demo;
	
	$sql="select filename,pic_ad_id from $pic_tbl where id=$aImgId";
	$res=q($sql);
	$row=mysql_fetch_array($res);
	$lAd_ID = $row["pic_ad_id"];
	$main_file=$row["filename"];
	$force=1;
	
	if ($set_demo==1)
	{	
		echo "<p>System in demo-mode. No delete</p>";
		return false;
	}

	
	$main_file=ereg_replace("_tmb2","",$main_file);
	$main_file=ereg_replace("_tmb1","",$main_file);
	$file_2=ereg_replace("\.","_tmb1.",$main_file);
	$file_1=ereg_replace("\.","_tmb2.",$main_file);
	
	if (file_exists("$set_path/images/$main_file")) { 
		$delete_result = unlink("$set_path/images/$main_file"); 
	}
	if (file_exists("$set_path/images/$file_2")) { 
		$delete_result = unlink("$set_path/images/$file_2"); 
	}
	if (file_exists("$set_path/images/$file_1")) { 
		$delete_result = unlink("$set_path/images/$file_1"); 
	}
	
	if ($force==1)
		$delete_result=1;
		
	if ($delete_result)
	{
		
		$sql = "delete from $pic_tbl where id = '$aImgId'";
		$r = q($sql);
		
		if (mysql_affected_rows())
		{
			$sq = "UPDATE $ads_tbl set ad_has_picture = ad_has_picture-1 where ad_id=$lAd_ID AND ad_has_picture > 0";
   			$result = q($sq);
   			return true;
		}
	}
	else
	{
		failMsg("Could not delete","The image has already been deleted, or the permission on the image
		dir/file is wrong. IMAGE: $main_file");
	}
	
}
/*** Update Expired Credits Esta funcion es un clon de la siguiente, hecha por JMR, 
     pero para enviar mails y borrar los creditos que expiraron                  **/
function updateExpireUserCredits($debug)
{
	global $set_warning_time,$set_url,$usr_tbl,$ads_tbl,$set_sitename,$set_webmaster_address,$set_advanced_delete_activated;
	
	$arrayOfTimeStamp = array(); 
	$arrayOfTimeStamp[] = array( 'timestamp' => addDaysToTimeStamp(1,time())				, 'notified_mark' => 2 );
	$arrayOfTimeStamp[] = array( 'timestamp' => addDaysToTimeStamp($set_warning_time,time()), 'notified_mark' => 1 );
	
	
	if ($set_advanced_delete_activated)
	{
	
		// Find out who to delete
		$sql="DELETE FROM mvial_user_credits ";
		$sql.=" WHERE `pay_membership_expire` <=" . time();	
		$res=q($sql);		
		
		foreach ($arrayOfTimeStamp as $timestamp){
			// Find out who to warn...
			$sql="SELECT m.user_id, package_id, pname, m.mainType,user_email,user_name, m.`pay_membership_expire` ";
			$sql.="FROM mvial_user_credits m join mvial_user m1 ON m1.user_id=m.user_id ";
			$sql.="join mvial_packages m2 on  m.package_id = m2.pid ";
			$sql.="WHERE m.`pay_membership_expire`< ".$timestamp['timestamp']." AND package_id!=0 AND m.pay_credits>0 ";		
			$sql.=" AND ( ad_owner_notified<".$timestamp['notified_mark'].")";
			
			if($debug==1) 
				echo "Query ".$timestamp['notified_mark']." -- vencimientos: ".$sql."\n\n";
				
			$res=q($sql);		
			while ($row=mysql_fetch_array($res))
			{
				$user_id = $row["user_id"];
				$package_id = $row["package_id"];
				$mainType = $row["mainType"];
				
				$lAdTitle=$row["pname"];
				$lAdExpireDate=formatDateShort($row["pay_membership_expire"]);
				$lUserName=$row["user_name"];	
				$lUserEmail=$row["user_email"];
				$mainTypeName = getMainTypeName($mainType);
				
				$lAdTitle=unhtmlentities(EF_DE." ".$mainTypeName.": ".$lAdTitle);
				
				$lUrl="http://$set_url/member.php";
				$lWarn_ttl = formatString(unhtmlentities(LA_EXPIRE_CREDITS_SOON_TITLE), array("$lUserName"));
				if($timestamp['notified_mark'] == 2) $diasAntes = "24 hs";
				else if($timestamp['notified_mark'] == 1) $diasAntes = "7 días";
				$lWarn_msg = formatString(unhtmlentities(LA_EXPIRE_CREDITS_SOON_MSG), array("$lUserName","$lUserEmail","$set_sitename","$lAdTitle","$lUrl","$lAdExpireDate","$diasAntes"));
								
				//if($lUserEmail=='jmrodriguez1982@gmail.com'){
				if ($set_webmaster_address)
						sendEmail($lUserEmail,$set_webmaster_address,$lWarn_ttl,$lWarn_msg);
				//}
								
				$sql="update mvial_user_credits set ad_owner_notified=".$timestamp['notified_mark']." where user_id=$user_id and package_id=$package_id and mainType=$mainType";
				$r_notify=q($sql);
			}
		}
	} // End of advanced delete
}
/*********FIN Update expired credits ***/
function updateExpireAds($debug)
{
	global $set_warning_time,$set_url,$usr_tbl,$ads_tbl,$set_sitename,$set_webmaster_address,$set_advanced_delete_activated;
	
	$arrayOfTimeStamp = array(); //JMR: Modifique esto para que se hagan dos notificaciones una site dias antes y otra 1 día antes
	$arrayOfTimeStamp[] = array( 'timestamp' => addDaysToTimeStamp(1,time())				, 'notified_mark' => 2 );
	$arrayOfTimeStamp[] = array( 'timestamp' => addDaysToTimeStamp($set_warning_time,time()), 'notified_mark' => 1 );
	
	
	if ($set_advanced_delete_activated)
	{
	
		// Find out who to delete
		$sql="select ad_id from $ads_tbl";
		$sql.=" where ad_date_expire <=" . time();
		//$sql.=" AND ad_owner_notified=1";
		$res=q($sql);
		
		
		while ($row=mysql_fetch_array($res))
		{
			$lId=$row["ad_id"];
			delete_ad($lId);
		}

		foreach ($arrayOfTimeStamp as $timestamp){
			// Find out who to warn...
			$sql="select ad_date,ad_date_expire,ad_id,ad_title,user_name,user_email from $usr_tbl,$ads_tbl";
			$sql.=" where ad_owner=user_id AND ad_date_expire<".$timestamp['timestamp'];
			$sql.=" AND ( ad_owner_notified<".$timestamp['notified_mark'].")";
			
			if($debug==1) 
				echo "Query ".$timestamp['notified_mark']." -- vencimientos: ".$sql."\n\n";
				
			$res=q($sql);		
			while ($row=mysql_fetch_array($res))
			{
				$lId=$row["ad_id"];
				$lAdTitle=$row["ad_title"];
				$lAdExpireDate=formatDateShort($row["ad_date_expire"]);
				$lAdAddedDate=formatDateShort($row["ad_date"]);	
				$lUserName=$row["user_name"];	
				$lUserEmail=$row["user_email"];
				
				$lAdTitle=unhtmlentities($lAdTitle);
				
				$lUrl="http://$set_url/" . linkDetail($lId);
				$lWarn_ttl = formatString(unhtmlentities(LA_EXPIRE_AD_SOON_TITLE), array("$lUserName","$lUserEmail","$set_sitename","$lAdTitle"));
				if($timestamp['notified_mark'] == 2) $diasAntes = "24 hs";
				else if($timestamp['notified_mark'] == 1) $diasAntes = "7 días";
				$lWarn_msg = formatString(unhtmlentities(LA_EXPIRE_AD_SOON_MSG), array("$lUserName","$lUserEmail","$set_sitename","$lAdTitle","$lUrl","$lAdExpireDate","$diasAntes"));
				
				
				if ($set_webmaster_address)
					sendEmail($lUserEmail,$set_webmaster_address,$lWarn_ttl,$lWarn_msg);
				
				
				$sql="update $ads_tbl set ad_owner_notified=".$timestamp['notified_mark']." where ad_id=$lId";
				$r_notify=q($sql);
			}
		}
	} // End of advanced delete
}

function makePDF($aInputHtmlPath,$aOutPutPDFPath)
{
	if (!file_exists($aInputHtmlPath))
		return file_not_present;
		
	$file_pointer = fopen($html_file, "w");
	fwrite($file_pointer,$line);
	fclose($file_pointer);
	
	$commandString="htmldoc --webpage --firstpage toc --jpeg --permissions all -f $aOutPutPDFPath $aInputHtmlPath 2>&1";$command = exec($commandString,$output);
	exec($commandString);
	
	if (file_exists($aOutPutPDFPath))
		return true;
	else 
		return pdf_not_created;
}

function writeHeadLine($aCaption,$aColor)
{
	$aCaption = "<font color='$aColor'><b>$aCaption</b></font><br>";
	return $aCaption;
}
function getExtraFields($res)
{
	$i=0;
	while ($i < mysql_num_fields($res)) 
	{
		$meta = mysql_fetch_field($res, $i);
		//echo $meta->name . "<br>";
		if (ereg("^e_",$meta->name))
			$lExtraFieldArray[]=$meta->name;
			
		$i++;
	}
	return $lExtraFieldArray;
}


function getMandatoryValues($aLimitToTpl,$aLimitToType)
{
	global $q_tbl;
	$i=0;
	$sql="select q_field,q_mand,q_reg_exp,q_reg_exp_errormsg,q_question,q_include_search from $q_tbl WHERE 2>1";
	if ($aLimitToType==2) // User Fields
		$sql.=" AND q_user_only=1 AND q_tpl=1";
	elseif ($aLimitToType==1) // Ad Fields
	{
		if ($aLimitToTpl>0)
			$sql.=" AND (q_tpl=1 OR q_tpl=$aLimitToTpl) AND (q_user_only=0 OR q_user_only IS NULL)";
		else
			$sql.=" AND (q_user_only=0 OR q_user_only IS NULL) AND q_tpl=1";
	}
	$sql.= " order by q_seq asc";
	$res=q($sql);
	while ($row=mysql_fetch_array($res)) 
	{
		$lExtraFieldArray[$i]["q_field"]=$row["q_field"];
		$lExtraFieldArray[$i]["q_mand"]=$row["q_mand"];
		$lExtraFieldArray[$i]["q_reg_exp"]=$row["q_reg_exp"];	
		$lExtraFieldArray[$i]["q_include_search"]=$row["q_include_search"];	
		if ($row["q_question"])
			$lExtraFieldArray[$i]["q_question"]=strEnc(CONSTANT($row["q_question"]));
		if ($row["q_reg_exp_errormsg"])
			$lExtraFieldArray[$i]["q_reg_exp_errormsg"]=strEnc(CONSTANT($row["q_reg_exp_errormsg"]));	
		$i++;
	}
	return $lExtraFieldArray;
}

function getQuestions($aLimitToTpl,$aLimitToType) 
{
	/*
	This function fetch all questions filtered by template id and type (ad/user)
	*/
	global $q_tbl;
	$i=0;
	$sql="select q_field,q_mand,q_reg_exp,q_type,q_reg_exp_errormsg,q_question,q_catdescr,q_isurl from $q_tbl WHERE 2>1";
	if ($aLimitToType==2) // User Fields
		$sql.=" AND q_user_only=1 AND q_tpl=1";
	elseif ($aLimitToType==1) // Ad Fields
	{
		if ($aLimitToTpl>0)
			$sql.=" AND (q_tpl=1 OR q_tpl=$aLimitToTpl) AND (q_user_only=0 OR q_user_only IS NULL)";
		else
			$sql.=" AND (q_user_only=0 OR q_user_only IS NULL) AND q_tpl=1";
	}
	$sql.=" order by q_seq asc";
	$res=q($sql);
	while ($row=mysql_fetch_array($res)) 
	{
		$lExtraFieldArray[$i]["q_field"]=$row["q_field"];
		$lExtraFieldArray[$i]["q_mand"]=$row["q_mand"];
		$lExtraFieldArray[$i]["q_type"]=$row["q_type"];
		$lExtraFieldArray[$i]["q_isurl"]=$row["q_isurl"];
		$lExtraFieldArray[$i]["q_reg_exp"]=$row["q_reg_exp"];	
		if ($row["q_question"])
			$lExtraFieldArray[$i]["q_question"]=strEnc(CONSTANT($row["q_question"]));
		if ($row["q_reg_exp"])
			$lExtraFieldArray[$i]["q_reg_exp_errormsg"]=strEnc(CONSTANT($row["q_reg_exp_errormsg"]));
		if ($row["q_catdescr"])
			$lExtraFieldArray[$i]["q_catdescr"]=strEnc(CONSTANT($row["q_catdescr"]));	
		$i++;
	}
	return $lExtraFieldArray;
}

function getEFields($aTableName)
{	
	global $set_mysql_base;
	$res=q("show fields from $aTableName from $set_mysql_base");
	
	while ($row=mysql_fetch_array($res))
	{
		$lFieldArray[$i]["Field"]=$row["Field"];

		$i++;
		
		
	}
	return $lFieldArray;
}



function getPossibleOptions($lOptionFileNb)
{
	global $set_path, $lang, $language;
	if (!empty($_SESSION["la"]))
		$lang = "_" . $_SESSION["la"];
	else
		$lang = "_" . $language;
	$lFile="$set_path/admin/config/options/$lOptionFileNb".$lang.".txt";
	
	if (file_exists($lFile))
		$options = file($lFile);
	
	return $options;
}


function avoidSqlBreakDown($aValue)
{
	$aValue=strip_tags($aValue);
	$aValue=ereg_replace("\.","",$aValue);
	$aValue=ereg_replace("\\\$","",$aValue);
	$aValue=ereg_replace("<","",$aValue);
	$aValue=ereg_replace(">","",$aValue);
	$aValue=ereg_replace(" ","",$aValue);
	$aValue=ereg_replace("\|","",$aValue);
	return $aValue;
	
}

function untree($parent, $level,$catid,$addad)
{
	global $cat_tbl,$set_multilang_cat,$set_language;
	if ($set_multilang_cat)
		$parentsql = q("select * from $cat_tbl where cat_fatherid=$parent order by cat_name");
	else
		$parentsql = q("select cat_id,cat_name,cat_total,cat_allow_ads from $cat_tbl where cat_fatherid=$parent order by cat_name");
	$return="";
	if (!mysql_num_rows($parentsql))
	{
		return;
	}
	else
	{
		while($branch = mysql_fetch_assoc($parentsql))
		{
			if ($addad==1 AND $branch[cat_allow_ads]<>"on")
				$echo_this = "<option value='-1'";
			else 
				$echo_this = "<option value='$branch[cat_id]'";
			if (is_array($catid))
			{
				if (in_array($branch[cat_id],$catid))
					$echo_this.=" selected";
			}		
			elseif ($catid==$branch[cat_id])
				$echo_this.=" selected";
			$echo_this.=">";
			
			for ($x=1; $x<=$level; $x++)
				$echo_this .=  "&nbsp;&nbsp;&nbsp;";
			
			$lCatName="";
		  	// Check if user selected category exists
			if (!empty($_SESSION["la"]) AND $set_multilang_cat)
			{
		  		$lang_cat = "lang_" . $_SESSION["la"];
		  		if (!empty($branch["$lang_cat"]))
		  			$lCatName = strEnc($branch["$lang_cat"]);
			}
		  	
			// User has not set any prefered language..
			if (!$lCatName)	
			{
				$lang_cat="lang_" . $set_language;
				if (!empty($branch["$lang_cat"]))
		  			$lCatName = strEnc($branch["$lang_cat"]); // Get default language, admin choise
		  		else 
		  			$lCatName = strEnc($branch["cat_name"]); // Last resort, use original name..
			}
			
			$echo_this.=$lCatName;
			
			if ($branch[cat_total]>0 AND $addad!==2)
				$echo_this.=" (". $branch[cat_total] . ")";
			elseif ($addad!==2)
				$echo_this.=" (0)";
			
			if ($branch[cat_allow_ads]=="on" AND $addad==1)
				$echo_this.=" *";
				
			$echo_this.="</option>";
			$return.=$echo_this;
			$rename_level = $level;
			$return.=untree($branch[cat_id], ++$rename_level,$catid,$addad);
			
		}
	}
	return $return;
}
function getCategoriesDD($catid,$addad)
{
	global $cat_tbl,$set_multilang_cat,$set_language,$set_cat_sort;
	
	$sql = "select cat_id,cat_name,cat_total,cat_allow_ads,cat_fatherid";
	if ($set_multilang_cat)
	{
		$lLangSupportedArray=split(",",$set_multilang_cat);
		foreach ($lLangSupportedArray as $lItem)
			$sql.=",lang_" . $lItem;
	}
	$sql.=" from $cat_tbl where cat_fatherid=0 order by $set_cat_sort";

	$lRes=q($sql);
	while ($row_cat = mysql_fetch_array($lRes))
	{
		if ($addad==1 AND $row_cat["cat_allow_ads"]<>"on")
			$string.="<option value='-1'";
		else
			$string.="<option value='$row_cat[cat_id]'";
		
		if (is_array($catid))
		{
			if (in_array($row_cat[cat_id],$catid))
				$string.=" selected";
		}	
		elseif ($catid==$row_cat[cat_id])
			$string.=" selected";
		
		$lCatName="";
	  	if ($set_multilang_cat)
			$lCatName = $row_cat["lang_" . $set_language];
		if (!$lCatName)
			$lCatName = $row_cat["cat_name"]; // Last resort, use original name..
		
		
		$string.=">" .$lCatName . "";
		if ($row_cat[cat_total]>0 && $addad!==2)
			$string.=" (". $row_cat[cat_total] . ")";
		elseif($addad!==2)
			$string.=" (0)";
		
		if ($addad==1 AND $row_cat["cat_allow_ads"]=="on")	
			$string.=" *";	
		$string.="</option>";
		$string.=untree($row_cat[cat_id], 1,$catid,$addad);
	}
	
	return $string;
}


function flat_untree($parent, $level,$catid,$addad)
{
	global $cat_tbl;
	$parentsql = q("select cat_id,cat_name,cat_total,cat_allow_ads from $cat_tbl where cat_fatherid=$parent order by cat_name");
	$return="";
	if (!mysql_num_rows($parentsql))
	{
		return;
	}
	else
	{
		while($branch = mysql_fetch_row($parentsql))
		{
		
			$lNum=$branch[2];
			if (!$lNum)
				$lNum=0;
			$return.="<tr><td>";
			for ($x=1; $x<=$level; $x++)
				$return .=  "&nbsp;&nbsp;&nbsp;";
			$return.="$branch[1]</td><td>$lNum</td>";
			$return.="<td>";
			if ($branch[3]=="on")
				$return.="<font color='green'>Yes</font>";
			else 
				$return.="<font color='red'>No</font>";
			$return.="</td>";
			
			$return.="<td><a href='?edit=$branch[0]'>Edit</a></td></tr>";
			$rename_level = $level;
			$return.=flat_untree($branch[0], ++$rename_level,$catid,$addad);
			
		}
	}
	return $return;
}
function flat_getCategoriesDD($catid,$addad)
{
	global $cat_tbl;
	$compsql = q("select cat_name,cat_total,cat_id,cat_allow_ads from $cat_tbl where cat_fatherid=0 order by cat_name");
	
	while ($categories = mysql_fetch_array($compsql))
	{
		$lNum=$categories[cat_total];
			if (!$lNum)
				$lNum=0;
		$string.="<tr class='rowColor2'><td>".strEnc($categories[cat_name])."</td><td>$lNum</td>";
		$string.="<td>";
		if ($categories["cat_allow_ads"]=="on")
			$string.="<font color='green'>".LA_ADMIN_YES."</font>";
		else 
			$string.="<font color='red'>".LA_ADMIN_NO."</font>";
		$string.="</td>";
		$string.="<td><a href='?edit=$categories[cat_id]'>Edit</a></td></tr>";
		$string.=flat_untree($categories[cat_id], 1,$catid,$addad);
	}
	
	return $string;
}

function getCategoryChildren($parent)
{
	global $cat_tbl;
	$parentsql = q("select cat_id from $cat_tbl where cat_fatherid=$parent");
	$return="";
	if (!mysql_num_rows($parentsql))
	{
		return;
	}
	else
	{
		while($row = mysql_fetch_row($parentsql))
		{
			$return.= "," . $row[0];
			$retTmp=getCategoryChildren($row[0]);
			if ($retTmp)
				$return.=",". $retTmp;
		}
	}
	$return=substr($return,1);
	return $return;	

}

function ban($aBanlist, $aEmail) 
{ 
	global $la_error_msg23;
	global $la_error;
	global $bans;
	
	$lBanlist=$aBanlist;
	$lEmail=strToDb($aEmail);
	
	foreach($lBanlist as $banned) 
	{ 
		$email_banned = explode("@", $banned); 
		if ($email_banned[0] == "*") 
		{ 
			$email_check = explode("@", $lEmail); 
	        if (trim(strtolower($email_check[1])) == trim(strtolower($email_banned[1]))) 
	        {
	               $stop = 1;
	               $lError_str.="<li type='square' class='warn_intend'>".LA_ERROR_MSG30."</li>";
	        }
		} 
	   	else 
		{ 
           	if (trim(strtolower($lEmail)) == trim(strtolower($banned))) 
            {
            	$stop = 1;
            	$lError_str.= "<li type='square' class='warn_intend'>".LA_ERROR_MSG30."</li>";
         	} 
		}	 
	}
	return $lError_str; 
	 
} 


function addLoginItem($aUserID)
{
	global $usr_tbl;
	if (!empty($aUserID))
	{
		q("update $usr_tbl set user_num_login=0 where user_id=$aUserID AND (user_num_login IS NULL OR user_num_login='')"); // Counter is not correct if the inital data for some reason isn�t default 0 in MySql
		
		// Record login
		$r1=q("update $usr_tbl set user_date_last_login=".time()." where user_id = $aUserID");
		$r2=q("update $usr_tbl set user_num_login=user_num_login+1 where user_id = $aUserID");
	}
}

function writeCommonAdminTable($aHeadLine, $aSection)
{
	global $set_template_dir;
	
	if (!$set_template_dir)
    		$set_template_dir="templates_old";
    	
    if (isset($_SESSION["set_template_dir"]))
    	$set_template_dir=$_SESSION["set_template_dir"];
    	
    if ($set_template_dir=="templates_new")
    {
    	
    	writeCommonAdminTable2($aHeadLine,$aSection);
    }
    else 
    {	
    	
	
	if ($aSection==1)
		echo "<table border='1' cellpadding='3' cellspacing='0' width='800' class='blackBorderTable'><tr><td class='trHeadLine'><b>$aHeadLine</b></td></tr><tr><td width='100%'>";		 
	else 
		echo "</td></tr></table>";
		
    }
 	
}

function writeCommonAdminTable2($aHeadLine, $aSection)
{
	if ($aSection==1)
		echo "<table cellspacing='0' class='box' style='background:none;border:none;'><tr><th colspan='2'><b>$aHeadLine</b></th></tr><tr><td width='100%'>";		 
	else 
		echo "</td></tr></table>";
 	
}

function remote_file_exists ($url) 
{ 

   $head = ""; 
   $url_p = parse_url ($url); 
   
   if (isset ($url_p["host"])) 
   { $host = $url_p["host"]; } 
   else 
   { return 1; } 
   
   if (isset ($url_p["path"])) 
   { $path = $url_p["path"]; } 
   else 
   { $path = ""; } 
   
   $fp = @fsockopen ($host, 80, $errno, $errstr, 20); 
   if (!$fp) 
   { return 2; } 
   else 
   { 
       $parse = parse_url($url); 
       $host = $parse['host']; 
       
       fputs($fp, "HEAD ".$url." HTTP/1.1\r\n"); 
       fputs($fp, "HOST: ".$host."\r\n"); 
       fputs($fp, "Connection: close\r\n\r\n"); 
       $headers = ""; 
       while (!feof ($fp)) 
       { $headers .= fgets ($fp, 128); } 
   } 
   fclose ($fp); 
   $arr_headers = explode("\n", $headers); 
   $return = false; 
   if (isset ($arr_headers[0])) 
   { $return = strpos ($arr_headers[0], "404") === false; } 
   return $return; 
} 

function colorSwitch($aStyle)
{
	$lStyleColor=$aStyle;
	if ($lStyleColor=="rowColor1")
		return "rowColor2";
	else if ($lStyleColor=="rowColor2") 
		return "rowColor1";
	else 
		return "rowColor2";
	
}

function getFileList($aDirectory,$aExtensions,$aSelected)
{
	global $set_path;
	$dir = opendir($set_path . "/". $aDirectory);
	$list="<option></option>";	
	while ($file = readdir($dir))
  	{
  		if ($file <> "." AND $file <> "..")
        {
    	
        	foreach ($aExtensions as $item)
    		{
        		if (eregi($item,$file))
    				$list.="<option value='$file'";
    				if ($file==$aSelected)
    					$list.=" selected";
    				$list.=">$file</option>";    	
    		}
		}
  	}
  	closedir($dir);
	return $list;
}

function getCategoriesDD_LIMITED($aSelected)
{
	$sql="select cat_id as drop_id,cat_name as drop_value,cat_childof from categories order by cat_sortnb asc";
	return getSpecialDropDown_LIMITED($sql,$aSelected);
}

function getDDFromList($arrOption,$aSelected)
{
	$str="";
	foreach ($arrOption as $key => $value) 
	{
		$drop_id = $key;
 		$drop_value = $value;
 		

		$str.= "<option value='$drop_id'";
		if (is_array($aSelected))
		{
			foreach ($aSelected as $item)
			{
				if ($item==$drop_id)
					$str.= " selected";
	
			}
			
		}
		else 
		{
			if ($aSelected==$drop_id)
				$str.= " selected";
		}
		$str.=">";
		$str.="$drop_value</option>";
	}
	return $str;	
}

function getDropDown($aSQL,$aSelected)
{
	
	$res=q($aSQL);
	$str="";
	while ($row = mysql_fetch_array($res))
	{
		$drop_id = $row["drop_id"];
 		$drop_value = $row["drop_value"];
 		

		$str.= "<option value='$drop_id'";
		if (is_array($aSelected))
		{
			foreach ($aSelected as $item)
			{
				if ($item==$drop_id)
					$str.= " selected";
	
			}
			
		}
		else 
		{
			if ($aSelected==$drop_id)
				$str.= " selected";
		}
		$str.=">";
		//$drop_value=strtolower($drop_value);
		//$drop_value=ucwords($drop_value);
		$str.="$drop_value</option>";
	}
	return $str;	
}

function getCategoryTemplates($aSelected) {
	global $template_tbl;return getDropDown("select tplid as drop_id,name as drop_value from $template_tbl order by tplid","$aSelected");
}
function getSubcategoryOrderBy($aSelected) {
	global $cat_tbl;return getDropDown("SHOW FIELDS['Field'] as drop_id,FIELDS['Field'] as drop_value  FROM $cat_tbl","$aSelected");
}

function redirect($aPage)
{
	echo "<Script language=\"javascript\">";
	echo "window.location=\"$aPage\"";
	echo "</script>";	
	echo "<p>Javascript is disabled in your browser.  <a href='$aPage'>Click here</a> to continue.</p>";
}

function notifyMembersNewAd($ad_cat_id,$catname,$ad_id,$ad_title,$ad_description,$aUrl)
{
	
	global $not_tbl,$usr_tbl,$set_sitename,$set_webmaster_address,$set_debug,$ads_tbl,$cat_tbl,$set_url;
	$lSQL="select * from $not_tbl,$usr_tbl,$ads_tbl,$cat_tbl WHERE user_id=notify_user_id AND ad_cat_id=cat_id AND notify_cat=cat_id AND notify_cat=$ad_cat_id AND ad_id=$ad_id AND ad_owner<>notify_user_id";
	
	$lRes=q($lSQL);
	
	$lUrl=eregi_replace("http://","",$aUrl);
	
	while ($row=mysql_fetch_array($lRes))
	{
		$lEmail=$row["user_email"];
		$lName=$row["user_name"];
		$lAdTitle=$row["ad_title"];
		$lCatName=$row["cat_name"];
		$lSendTo=$lEmail;
		$lSendFrom=$set_webmaster_address;
	
		$lNotifyArray=array("$lName","$lEmail","","$set_sitename","".getRemoteIp()."","http://$set_url/member_login.php","http://$set_url/" . linkDetail($ad_id),"$lCatName","$lAdTitle");
		$lSubject = formatString(LA_MAIL_WATCHNOT_SUBJECT, $lNotifyArray);
		$lBody = formatString(LA_MAIL_WATCHNOT_BODY, $lNotifyArray);
		
		if ($set_debug)
			echo "$lTitle<hr>$lSubject<hr>$lBody<hr>$lSendTo<hr>$lSendFrom";
	
		sendEmail($lSendTo,$set_webmaster_address,$lSubject,$lBody);	
	}
}


function copyr($source, $dest)
{
	// Simple copy for a file
    if (is_file($source)) {
    	
    	 
    	$res=copy($source, $dest);
    	if (file_exists($dest))
    		chmod($dest, 0777);
    	return $res;
        
    }
    
    if (file_exists($dest))
    	chmod($dest, 0777);
  

    // Loop through the folder
    $dir = dir($source);
    while (false !== $entry = $dir->read()) {
        // Skip pointers
        if ($entry == '.' || $entry == '..') {
            continue;
        }
 
        // Deep copy directories
        if ($dest !== "$source/$entry") {
        	
        	if (!eregi("templates_c",$entry) AND !eregi("cache",$entry))
        	{
        		if (!file_exists($dest))
					mkdir ($dest, 0777);
	
				$lFile.="$source/$entry,";
        		copyr("$source/$entry", "$dest/$entry");
        		//echo "$dest/$entry";
        		
				
        		@chmod($dest, 0777);
        		@chmod("$dest/$entry", 0777);
        	}
        }
    }
 
    
    // Clean up
    return $lFile;
}



function rm($dir) {
   if(!$dh = @opendir($dir)) return;
   while (($obj = readdir($dh))) {
       if($obj=='.' || $obj=='..') continue;
       if (!@unlink($dir.'/'.$obj)) rm($dir.'/'.$obj);
   }
   
}



function urlBar($aNumRecords,$aNumPerPage,$aPage,$aUrl)
{
	global $set_url;
	if (!$aPage)
		$aPage=1;
		
	$pagerArray=getPagerData($aNumRecords,$aNumPerPage,$aPage);
	$urlBar="<table width='100%' border='0'><tr><td align='left' width='110'>";
	
	if ($aPage==1)
		$urlBar.="";
	else 
		$urlBar.="<a href=\"?page=" . ($aPage-1) . "$aUrl\" class='button'>&lt; ".LA_PREV_N."</a>";	

	$urlBar.="</td><td align='center' >";
	/*if ($pagerArray["numPages"]<35)
	{*/
	for ($c=1;$c<=$pagerArray["numPages"];$c++)
	{
		if ($aPage==$c)
			$urlBar.=" <b>$c</b> ";
		else 
			$urlBar.=" <a href=\"?page=" . ($c) . "$aUrl\">$c</a> "; 		
	}
	/*}*/
	$urlBar.="</td><td align='right' width='110'>";	
	
	
	if ($aPage == $pagerArray["numPages"] || $pagerArray["numPages"]==0)
       	$urlBar.=""; 
    else
    {
		$urlBar.="<a href=\"?page=" . ($aPage+1) . "$aUrl\" class='button'>" . LA_NEXT_N . " &gt;</a>"; 
    }
	$urlBar.="</td></tr></table>";
	
	$offset=$pagerArray["offset"];
	if ($offset<0)
		$offset="0";
	$sql=" limit " . $offset . "," . $pagerArray["limit"];	
	
	$returnArray["url_bar"]=$urlBar;
	$returnArray["sql_limit"]=$sql;
	
	return $returnArray;
	
	
}
function timeStart()
{
	global $begintime; 
	$time = microtime();
	$time = explode(' ', $time);
	$time = $time[1] + $time[0];
	$begintime = $time;

}
function timeStop()
{
	global $begintime;
	$time = microtime();
	$time = explode(" ", $time);
	$time = $time[1] + $time[0];
	$endtime = $time;
	$totaltime = ($endtime - $begintime);
	echo 'PHP parsed this page in ' .$totaltime. ' seconds.';
}
function getPagerData($numHits, $limit, $page) 
{ 
   $numHits  = (int) $numHits; 
   $limit    = max((int) $limit, 1); 
   $page     = (int) $page; 
   $numPages = ceil($numHits / $limit); 

   $page = max($page, 1); 
   $page = min($page, $numPages); 

   $offset = ($page - 1) * $limit; 

   $ret["offset"]=$offset; 
   $ret["limit"]=$limit; 
   $ret["numPages"]=$numPages; 
   $ret["page="]= $page; 
   
   return $ret; 
}  
function makeOrder($aPackage,$aUser,$aDate,$aPrice,$aCantidad=1)
{
	global $pay_tbl;
	if(!isFreePackage($aPackage)){
		$sql = "insert into $pay_tbl (o_package,o_user,o_date,o_amount,o_cantidad) values(". $aPackage . ", '".$aUser."',". $aDate . ", '" . $aPrice*$aCantidad. "',".$aCantidad.")";
	}else{
		$sql = "insert into $pay_tbl (o_package,o_user,o_date,o_amount,o_date_paid,o_status,o_cantidad) select ". $aPackage . ", '".$aUser."',". $aDate . ", '" . $aPrice . "',".time().",'Paid',1 from (select 1) as aux where exists(
		select count(o_package) as countp from mvial_orders where o_user=$aUser and o_package=$aPackage group by o_package having countp<".FREE_PACKAGE_COUNT.")".
		" or not exists(select o_package from mvial_orders where o_user=$aUser and o_package=$aPackage) ";
	}
	$res=q($sql);
	logMsg("make order Query","order creada: ".$sql);		
	return mysql_insert_id();		
}

function completeOrder($aOrderid,$aStatus,$aVendor,$aAmount,$package_id)
{
	global $usr_tbl,$pay_tbl;
	$sql = "update $pay_tbl set o_status = '$aStatus',o_vendor= $aVendor,o_date_paid=".time().", o_amount='".str_replace(",", ".",$aAmount)."' where o_id=$aOrderid";
	$res=q($sql);
	/*JMR: Una vez que la Orden fue pagada movemos los avisos de TEMP a AD*/
	if($aStatus=="Paid"){
		$lRes=q("SELECT m.o_user,a.mainType FROM mvial_orders m inner join mvial_packages a on m.o_package=a.pid where m.o_id=$aOrderid LIMIT 1");
		
		if($row = mysql_fetch_array($lRes)){
			 habilitarAvisosDisabled($row["mainType"],$row["o_user"],$package_id);
		}
	}
	/**END: JMR modification*/	
}

function isVendor($aUserID)
{
	global $usr_tbl;
	$lSql = "select user_is_vendor from $usr_tbl where user_id=$aUserID limit 1";
    $lRes=q($lSql);
    $lRow=mysql_fetch_array($lRes);
    $lisVendor = $lRow["user_is_vendor"];
    if ($lisVendor==1)
    	return true;
    else 
    	return false;
}

function addPackage($user,$package,$aOrderid=0)
{

	global $usr_tbl,$pkg_tbl,$pay_tbl;
	
	$cantidad=1;
	if($aOrderid!=0){
		$psqlOrder= "select o_cantidad from $pay_tbl where o_id=".$aOrderid." limit 1";
		$resultOrder=q($psqlOrder);
		$rowOrder=mysql_fetch_array($resultOrder);
		if($rowOrder){
			$cantidad=$rowOrder["o_cantidad"];
		}
	}
	
	$psql= "select * from $pkg_tbl where pid=$package";
	$result=q($psql);
	$row=mysql_fetch_array($result);
	if($row["concesionaria"] == 1){
		$cantidad = $row["avisos"];
		$lExpire=addDaysToTimeStamp($row["pdur"]*$cantidad,time());		
		// Actualizo el estado de Vendor del usuario
		setVendorStatus($user);
	}else
		$lExpire=addDaysToTimeStamp($row["pdur"],time());
		
	$mySQL="SELECT count(*) as count FROM mvial_user_credits m where m.user_id=".$user." and m.mainType=".$row['mainType']." and m.package_id=".$package;
	$result2=q($mySQL);
	$row2=mysql_fetch_array($result2);
	$existeUnPaquete = $row2["count"]; 
	if($existeUnPaquete==0){
		$sql= "INSERT INTO  mvial_user_credits (user_id,pay_membership_expire,pay_credits,pay_bold,pay_num_images,pay_upload,pay_wysiwyg,
        pay_vendor,pay_premium,pay_upload_video,mainType,package_id )
        VALUES($user,'$lExpire',".$row["avisos"]*$cantidad.",".$row["pmessages"]*$cantidad.",".$row["pupload"]*$cantidad.",".$row["pupload"]*$cantidad.",0,";
	    if (isVendor($user))
		  $sql.="1,";
		else
			$sql.=$row["pgb"]*$cantidad.",";     
	 	    $sql.=$row["ppremium"]*$cantidad.","; 
        	$sql.=$row["pmatch"]*$cantidad.",";
        	$sql.=$row["mainType"].",";
        	$sql.=$row["pid"].")";    
	
	}else{
		$sql= "UPDATE mvial_user_credits SET				 
				    pay_membership_expire = '".$lExpire."',
				    pay_credits = pay_credits +". $row["avisos"]*$cantidad.",
				    pay_bold = pay_bold+".$row["pmessages"]*$cantidad.",
				    pay_num_images = pay_num_images+".$row["pupload"]*$cantidad.",
				    pay_upload = pay_upload+".$row["pupload"]*$cantidad.",";
		if (isVendor($user))
		  $sql.="pay_vendor=1,";
		else
		  $sql.="pay_vendor=" . $row["pgb"]*$cantidad.",";				    		    
		$sql.= " pay_premium = pay_premium+".$row["ppremium"]*$cantidad.",
				 pay_upload_video = pay_upload_video+".$row["pmatch"]*$cantidad." WHERE  user_id = ".$user." AND mainType = ".$row['mainType'].
				 " AND package_id = ".$row['pid'];
		
	}
	//logMsg("AddPackage",$sql);
	$res2=q($sql);
	
}

/**
 * void updateVendorStatus: Se hace 'VENDOR' al usuario especificado
 * @params int idusuario	Número ID del usuario (Tabla mvial_user)
 */
function setVendorStatus ( $idusuario ){
	if (is_numeric($idusuario)){
		$sqlHacerVendor="update mvial_user set user_is_vendor=1 where user_id={$idusuario}";
		q($sqlHacerVendor);
	}
}

function getExpireStatus($aUserID)
{
    global $usr_tbl;
    $sql="select user_id, pay_membership_expire from $usr_tbl where user_id=" . $aUserID . " AND pay_membership_expire>".time()." limit 1";
    $res=q($sql);
    $row=mysql_fetch_array($res);
    if ($row["user_id"]>0)
    {
        return true;
    }
    else
    {
        if($row["pay_membership_expire"] <> 0)
        	q("update $usr_tbl set user_is_vendor=0 where user_id=".$aUserID."");
        
        return false;
    }
}


function encodeHTML($sHTML)
{
	$sHTML=ereg_replace("&","&amp;",$sHTML);
	$sHTML=ereg_replace("<","&lt;",$sHTML);
	$sHTML=ereg_replace(">","&gt;",$sHTML);
	return $sHTML;
}


function criticalError($lHeadLine,$lError)
{
	global $set_path,$set_url,$sitename;
	
	//include_once("header_inc.php");
	$tplError=new TplLoad();	
	$tplError->assign("title","$lHeadLine");
	$tplError->assign("msg","$lError");	
	$tplError->assign("url","http://$set_url");	
	$tplError->assign("sitename","$sitename");	
	$tplError->display("general_error.tpl");
	include_once("footer_inc.php");
	exit;
}

function build_hierarchy($id, $vn, $idfn, $pidfn, $cfn, $lfn) {
	global $cat_tbl,$set_multilang_cat,$language;
	if ($id == 0) echo 'var '.$vn.' = [';
	$sql = "SELECT * FROM $cat_tbl WHERE $pidfn=$id";
	$result = q($sql);
	if (mysql_num_rows($result) == 0) return;
	while ($row = mysql_fetch_assoc($result)) {
		if(!$vn) echo ',';
		$vn = 0;
		$clink = $row[$lfn];
		$cid = $row[$idfn];
		$allowads = $row["cat_allow_ads"];
		$num_ads = $row["cat_total"];
		$catname=addslashes($row[$cfn]);
		
		if (!empty($_SESSION["la"]) AND $set_multilang_cat)
		{
			$lang_cat = "lang_" . $_SESSION["la"];
			if (!empty($row["$lang_cat"]))
  				$catname = $row["$lang_cat"];				
		}
		
		echo " ['" . "$catname ($num_ads)";
		if ($allowads=="on")
			echo " *";
		echo "', \"javascript:linkCheck('$clink|$allowads')\", ";
		if($id == 0) echo "{'st':0}";
			else echo "0";
		build_hierarchy($cid, $vn, $idfn, $pidfn, $cfn, $lfn);
		echo ']';
	}
	mysql_free_result($result);
	if($id == 0) echo "];";
}

function checkWrite($aPath,$aPerm,$aSimpleReturn)
{
	$lOK=false;
	// First simple permission check
	clearstatcache(); 
    $configmod = substr(sprintf('%o', fileperms($aPath)), -4);  
    if ($configmod == $aPerm) 
    	$lOK=true;
	
	// File is NOT correct CHMOD�n. Due to bugs in some system, also check real file create
	$fp=@fopen($aPath . "/test.inc","w+");
	@fwrite($fp,"Testfile");
	if (file_exists($aPath . "/test.inc"))
	{
		$lOK=true;
		@chmod($aPath . "/test.inc",octdec($aPerm));
		@unlink($aPath . "/test.inc");
		
	}
	@fclose($fp);
	
	if ($lOK)
		$returnArray["writeable"]=$lOK;
	$returnArray["permission"]=$configmod;	

	if ($aSimpleReturn==1 && $lOK==true)
		return true;
	else
		return $returnArray;
    
}

function portScan($host,$port)
{
	$fp = fsockopen($host, $port, $errno, $errstr, 4 );
	return $fp;
}
function getStarRating($aScore)
{
	$lFullStars=floor($aScore/2);
	$lNoneStars=$aScore-$lFullStars;
	
	if ($lNoneStars>=0.5)
		$lHalfStars=1;
	else 
		$lHalfStars=0;
	$lStr="";
	$lNumUsed=0;
	for ($st=1;$st<6;$st++)
	{
		if ($lFullStars>=$st)
			$lStr.="<img src='layout_images/new/star_full.gif' align='left' alt='' />";
		elseif ($lHalfStars>0 && !$lNumUsed)
		{
			$lStr.="<img src='layout_images/new/star_half.gif' align='left' alt='' />";
			$lNumUsed=1;
		}
		else 
			$lStr.="<img src='layout_images/new/star_empty.gif' align='left' alt='' />";
	}
	return $lStr;
 
}

function createUser($aEmail,$aPass,$aName,$aEmelding,$aHideEmail,$aVerifyCode,$aExtraFields)
{
	global $usr_tbl,$set_inform_admin_joined,$set_webmaster_address;
	
	
	
	if (!$aEmail)
		failMsg("Critical Error","Email missing");
	
	if ($aVerifyCode)
		$p=$aPass;
		
	$aEmail=strToDb($aEmail);
	$aPass=strToDb($aPass);
	$aName=strToDb($aName);
	$aEmelding=strToDb($aEmelding);
	$aHideEmail=strToDb($aHideEmail);
	$aVerifyCode=strToDb($aVerifyCode);
	
		
		
	$sql = "insert into $usr_tbl (user_pass_plain,user_pass_md5,user_email,user_name,user_newsletter,user_hide_email,user_verify_code,user_date)"; 
	$sql.=" values 	('$p',md5('$aPass'), '$aEmail', '$aName', '$aEmelding','$aHideEmail','$aVerifyCode', ".time() .")";
	$result = q($sql);	
	$user_id=mysql_insert_id();
	
	if ($user_id>0)
	{
		addToHistory(5,$user_id,"","");
		
		if ($user_id>0 && $aExtraFields)
			updateSelected($aExtraFields,"",$user_id);
		
			
		if ($set_inform_admin_joined)
		{
			$time=time();
			$lIP = strToDb(getRemoteIp());
			$subject = formatString(LA_NEW_MEMBER_TITLE,array("$aName","$aEmail",formatDateLong(time()),"$lIP"));
			$body = formatString(LA_NEW_MEMBER_MSG,array("$aName","$aEmail",formatDateLong(time()),"$lIP"));
			sendEmail($set_webmaster_address,$aEmail,$subject,$body);
		}	  
	}	
	
	return $user_id;
	
}
function checkValid()
{
	global $set_li,$set_url;
	if ($_SESSION["buffer"])
		return $_SESSION["buffer"];

	if (@ini_get("allow_url_fopen"))
	{
		$WebFile = "http://www.deltascripts.com/licence_server.php?licence_check=1&li=$set_li&url=$set_url";
		$handle = fopen ($WebFile, "r");
		
		while (!feof($handle)) 
		{
			$buffer=fread($handle,10000);
			$_SESSION["buffer"]=$buffer;
		 	return $buffer;
		}
	}
	else 
	{
		$_SESSION["buffer"]="Valid licence";
		return "Valid licence";

	}
	
}

function getRegionName($aRegionID)
{
	global $reg_tbl;
	$lSql="select reg_name from $reg_tbl where reg_id=$aRegionID";
	$lRes=q($lSql);
	$lRow=mysql_fetch_array($lRes);
	return $lRow["reg_name"];
}


function createAd($aUserID,$aTitle,$aDescr,$aCat,$aExpireAfterDays,$aSpecial,$aPremium,$aExtraFields,$aNotifyAdmin,$aRegion,$precio,$moneda,$aLocalidad,$laProvincia = null,$packageID = 0)
{
	global $ads_tbl,$cat_tbl,$set_url,$set_webmaster_address,$set_nl2br,$sel_tbl;
	
	/*JMR: Verificamos que existan creditos, aunque no los modificamos. Si no existen, verificamos que haya
	 *     al menos una orden hecha si esta existe el aviso se crea como vencido	*/
	$mainType = getPaqueteMainType($aCat);
	$creditos=obtenerCreditosExistentesPorCategoria($mainType,$aUserID,$packageID);
	/*JMR: Obtenemos el tipo de paquete, si fuese cero verificamos la variable de session. Sino está seteado ahí --> error. Si es !=0
	 *     verificamos que sea un paquete valido para dicho usuario si no es valido --> error*/
	if($packageID == 0){
		if(!empty($_SESSION['package_selected_id'])){
			$packageID = $_SESSION['package_selected_id'];			
		}
	}
	if(isset($_SESSION['package_selected_id'])) unset($_SESSION['package_selected_id']);
	if(empty($creditos) || $creditos<1){
		$query="SELECT coalesce(sum(m.o_cantidad),0) as cantidad FROM mvial_orders m inner join mvial_packages p ON m.o_package=p.pid where p.pid=$packageID and o_status='0' and o_user=".$aUserID."  and mainType=".$mainType;
		$lRes=q($query);
		if($row_cat = mysql_fetch_array($lRes)){
			$orders=$row_cat["cantidad"];
			$creditos=0;
		}
		if(empty($orders) || $orders<1){
			return -1;
		}
	}
	
	/*********************************************************************/
	/*if($aExpireAfterDays<1){
			$array = getUserCreditsinfo($aUserID,$packageID);
			$aExpireAfterDays = $array['pay_membership_expire'];
	}*/
	$lExpireDate=addDaysToTimeStamp($aExpireAfterDays,time());
	
	if ($set_nl2br)
		$lTitle=nl2br($aTitle);
	else 
		$lTitle=$aTitle;
		
	if (!is_integer($aUserID))
		failMsg("Critical Error","Owner ID was not integer");
	if (!$aCat)
		failMsg("Critical Error","Category ID missing");
	if (!$lTitle)
		failMsg("Critical Error","No title of ad");
	if ($aExpireAfterDays<1){
		failMsg("Critical Error","Expire After X days was 0, which is not allowed");			
	}
	
	// Check if category is ad_is_validated
	$sql="select cat_id from $cat_tbl where cat_id=$aCat";	
	$r=q($sql);
	if (mysql_num_rows($r)<1)
		failMsg("Critical Error","Category $aCat doesn�t exists!");

	$aUserID=strToDb($aUserID);	
	$lTitle=strToDb($lTitle);
	$aDescr=strToDb($aDescr);
	$lRegion=strToDb($aRegion);
	if ($lRegion=="")
		$lRegion=0;

	//Find Provincia Id
	if($laProvincia!=null){
		//logMsg("JMR: Provincia:",$laProvincia);
		$res_prov=q("SELECT id FROM provincia p where nombre like '$laProvincia'");
		$row_prov=mysql_fetch_array($res_prov);
		$ProvinciaId=$row_prov["id"];
		if($ProvinciaId==null)
			$ProvinciaId='NULL';
	}else{
		$ProvinciaId='NULL';
	}
	/*
	 * Si el pago no fue confirmado se guarda en una tabla temporal
	 * */
	if($creditos==0){
		$enabled = "0";
	}else{
		$enabled = "1";
	}
		
	$sql="insert into $ads_tbl ";
	$sql.=" (ad_owner,ad_title,ad_description,ad_date,ad_cat_id,ad_date_expire,ad_is_special,ad_is_premium,ad_region,ad_precio,ad_moneda,ad_localidad_id,ad_provincia,ad_is_validated,ad_enabled,ad_package_id)";
	$sql.=" values(";
	$sql.="$aUserID,'$lTitle','$aDescr',".time().",$aCat,$lExpireDate,$aSpecial,$aPremium,$lRegion,$precio,'$moneda',NULL,$ProvinciaId,$enabled,$enabled,$packageID)";
	$res=q($sql);
	$id=mysql_insert_id();
	
	//JMR: creamos en este mismo instante la entrada en la tabla: mvial_ad_extra_options 
	q("INSERT INTO mvial_ad_extra_options(mv_ad_id,mv_package_id) values($id,$packageID)");
	//Luego será borrada y dada de alta correctamente con los datos que corresponden
	
	if ($id<1) // Auto Increment error (wrong db property)
		failMsg("Critical Database Error","Field ad_id wasn�t increased. Check that AutoIncrement is on.");
	
	if ($id>0)
	{
		if($creditos!=0){		
			addToHistory(6,$aUserID,$id,"");
			userAdsCounter($aUserID,1);	 // Increase counter for this user
			categoryCounter($aCat,1);
		}	
		//q("delete from $sel_tbl where sel_option_ad=$id");
		
		if ($aExtraFields)
		{
			updateSelected($aExtraFields,$id,"",$packageID);
		}
		
		if ($aNotifyAdmin==1)
		{
			// Notify administator that they have a new ad
			$url = "http://" . $set_url . "/detail.php?id=$id";
			$subject = formatString(LA_NEW_AD_INFO,array($id,$aTitle,$aDescr,$url,getRemoteIp()));
			$body = formatString(LA_NEW_AD_INFORM,array($id,$aTitle,$aDescr,$url,getRemoteIp()));			
			sendEmail($set_webmaster_address,$set_webmaster_address,$subject,$body);
			
		}
		return $id;
	}
}

//JMR: Esta funcion fue agregada para duplicar ciertos campos en la tabla principal de ADs a finde que se listen
function getFieldsIdtoDuplicate(){
	
	$marcaFields = array();
	$modeloFields = array();
	$potenciaFields = array();
	$horasKmFields = array();
	$anioFields = array();
	$localidadFields = array();
	
	$results=q("SELECT q_field,q_question FROM mvial_questions");
	while($value= mysql_fetch_array($results)){
		switch ($value['q_question']) {
		    case 'EF_MARCA':
		    	$marcaFields[]=$value['q_field'];
		        break;
		    case 'EF_MODELO':
		    	$modeloFields[]=$value['q_field'];
		        break;
		    case 'EF_POTENCIA':
				$potenciaFields[]=$value['q_field'];        
		        break;
		    case 'EF_HORAS':
				$horasKmFields[]=$value['q_field'];        
		    	break;    
			case 'EF_KM':
				$horasKmFields[]=$value['q_field'];        
		    	break;
			case 'EF_ANIO':
				$anioFields[]=$value['q_field'];        
		    	break;		    	
			case 'EF_USR_LOCALIDAD':
				$localidadFields[]=$value['q_field'];        
	    		break;
		}
	}
	return array("marca"=>$marcaFields,"modelo"=>$modeloFields,"potencia"=>$potenciaFields,"hskm"=>$horasKmFields,"anio"=>$anioFields,"localidad"=>$localidadFields);
		
}

//JMR: Esta función hace el insert en la base de datos, en la tabla "ad_extra_options" de los campos especiles (esta info es duplicada)
function insertSpecialFields($Ad,$marca,$modelo,$potencia,$hskm,$anio,$marcaStr,$localidad,$packageId){
	q("DELETE FROM mvial_ad_extra_options WHERE mv_ad_id=$Ad");
	
	$defPackageId = $packageId;
	
	if(empty($defPackageId)){
		$sql="SELECT ad_package_id FROM mvial_ad where ad_id=$Ad";
	    $res=q($sql);
	    if($row=mysql_fetch_array($res))	    
	    	$defPackageId = $row["ad_package_id"];
	    
	}
	
	if($marca!=-1){
		$sql="SELECT marca FROM marca where id=$marca";
	    $res=q($sql);
	    if($row=mysql_fetch_array($res))	    
	    	$marcaStr = $row["marca"];
	}
	
	q("INSERT INTO mvial_ad_extra_options(mv_ad_id,mv_marca,mv_modelo,mv_potencia,mv_hskms,mv_anio,mv_marca_str,mv_localidad_name,mv_package_id) values($Ad,'$marca','$modelo','$potencia','$hskm','$anio','$marcaStr','$localidad',$defPackageId)");
	
}

function updateSelected($aExtraFields,$aAd,$aUser,$packageId = 0)
{
	global $sel_tbl;
	//print_r($aExtraFields);
		
	if ($aAd)
	{
		q("delete from $sel_tbl WHERE sel_option_ad=$aAd");
		$lColumName="sel_option_ad";
		$lColumValue=$aAd;
		//JMR: 18-06-2009
		$specialFields = getFieldsIdtoDuplicate();
			//inicialización de los specialfields duplicados. En principio vacios
		$specialValues= array("marca"=>0,"modelo"=>"","potencia"=>"","hskm"=>"","anio"=>"","marcaStr"=>"","localidad"=>"");
		//END JMR
	}
	elseif ($aUser)
	{
		q("delete from $sel_tbl WHERE sel_option_user=$aUser");
		$lColumName="sel_option_user";
		$lColumValue=$aUser;
	}
	
	foreach ($aExtraFields as $lItem)
	{
		//logMsg("Lo' especiale': ",print_r($aExtraFields,TRUE));
		$lValue=$lItem["sel_option_id"];
		$lValueFieldNb=$lItem["sel_option_field"];
		$lText=$lItem["sel_option_text"];
		if ($lItem["sel_option_decimal"]!=null)
			$lDecimal=$lItem["sel_option_decimal"];
		else 
			$lDecimal="";
		$lSeq=$lItem["sel_option_seq"];
		
		//logMsg  ( LOG_WARNING  ,$lValue . " - " . $lValueFieldNb . " - " . $lText . " - ". $lValueFieldNb); //XXX LOG
		
		//JMR: 18-6-2009 en Cada ciclo verifico si tengo un campo especial para insertar en la tabla ad_extra_options
		if ($aAd)
		{
			
			//logMsg("Lo' especiale': ",print_r($specialFields,TRUE));
		
			foreach ($specialFields as $spKey => $spValue)
			{   
				if(in_array($lValueFieldNb, $spValue)){
					
										
					if ($spKey=='marca'){
						if ($spKey==$lText){
							$specialValues['marca']=$lValue;
						}else{
							$specialValues['marca']=-1;
							$specialValues['marcaStr']=$lText;
							
						}
					}else
						$specialValues[$spKey]=$lText;
					//break;
				}
			}
		}
		//END JMR
		
		if (is_array($lValue)) // If multiple options selected
		{
			foreach ($lValue as $lItemFromArray)
			{
				$lItemFromArray=strToDb($lItemFromArray);
				$lValueFieldNb=strip_tags(strToDb($lValueFieldNb));
				$lExtraSql="insert into $sel_tbl (sel_option_id,$lColumName,sel_option_field,sel_sort_nb) Values ($lItemFromArray,$lColumValue,$lValueFieldNb,'$lSeq');";
				$lExtraRes=q($lExtraSql);
			}		
		}
		else if ($lValue !="") // If single options selected
		{
			$lValue=strip_tags(strToDb($lValue));
			$lValueFieldNb=strip_tags(strToDb($lValueFieldNb));
			if ($lText !=""){
				$lExtraSql="insert into $sel_tbl (sel_option_text,sel_option_id,$lColumName,sel_option_field,sel_sort_nb) Values ('$lText',$lValue,$lColumValue,$lValueFieldNb,'$lSeq');";			
			}else{
				$lExtraSql="insert into $sel_tbl (sel_option_id,$lColumName,sel_option_field,sel_sort_nb) Values ($lValue,$lColumValue,$lValueFieldNb,'$lSeq');";
			}
			$lExtraRes=q($lExtraSql);
			//logMsg("JMR-2: Insert-Update ExtraFields",$lExtraSql);
		}
		else if ($lText !="") // If Text input
		{
			$lText=strip_tags(strToDb($lText));
			$lValueFieldNb=strip_tags(strToDb($lValueFieldNb));
			$lExtraSql="insert into $sel_tbl (sel_option_text,$lColumName,sel_option_field,sel_sort_nb) Values ('$lText',$lColumValue,$lValueFieldNb,'$lSeq');";
			$lExtraRes=q($lExtraSql);
		}
		else if ($lDecimal !="") // If Decimal input
		{
			$lText=strip_tags(strToDb($lText));
			$lValueFieldNb=strip_tags(strToDb($lValueFieldNb));
			//$lDecimal=ereg_replace("\.","$set_amount_decimal",$lDecimal);
			$lDecimal=ereg_replace(",","\.",$lDecimal);
			$lExtraSql="insert into $sel_tbl (sel_option_decimal,$lColumName,sel_option_field,sel_sort_nb) Values ('$lDecimal',$lColumValue,$lValueFieldNb,'$lSeq');";
			$lExtraRes=q($lExtraSql);
		}
		
		//echo $lExtraSql . "<br>";
	}
	//JMR: Insert final de los valores especiales
	if ($aAd)
	{
		insertSpecialFields($aAd,$specialValues["marca"],$specialValues["modelo"],$specialValues["potencia"],$specialValues["hskm"],$specialValues["anio"],$specialValues["marcaStr"],$specialValues["localidad"],$packageId);
	}
	
}

function updateAd($aAdID,$aUserID,$aTitle,$aDescr,$aCat,$aExpireAfterDays,$aSpecial,$aPremium,$aExtraFields,$aNotifyAdmin,$aRegion, $aPrice, $aMoneda, $aLocalidad,$aProvincia=null)
{
	global $ads_tbl,$cat_tbl,$set_url,$set_webmaster_address,$sel_tbl;
	
	$lExpireDate=addDaysToTimeStamp($aExpireAfterDays,time());

	if ($set_nl2br)
		$lTitle=nl2br($aTitle);
	else
		$lTitle=$aTitle;
		
	if (!is_integer($aUserID))
		failMsg("Critical Error","Owner ID was not integer");
	if (!$aCat)
		failMsg("Critical Error","Category ID missing");
	
	// Check if category is ad_is_validated
	$sql="select cat_id from $cat_tbl where cat_id=$aCat";	
	$r=q($sql);
	if (mysql_num_rows($r)<1){
		failMsg("Critical Error","Category $aCat doesn�t exists!");
	}

	// Find original posted category in later usage
	$res_cat=q("select ad_cat_id from $ads_tbl where ad_id=$aAdID");
	$row_cat=mysql_fetch_array($res_cat);
	$lOriginalCatid=$row_cat["ad_cat_id"];
	
	if(getPaqueteMainType($lOriginalCatid)!=getPaqueteMainType($aCat)){
		//Cambio invalido, dejamos la Categoria original
		$aCat = $lOriginalCatid;	
	}
		
	//Find Provincia Id
	if($aProvincia!=null){
		//logMsg("JMR: Provincia:",$aProvincia);
		$res_prov=q("SELECT id FROM provincia p where nombre like '$aProvincia'");
		$row_prov=mysql_fetch_array($res_prov);
		$ProvinciaId=$row_prov["id"];
	}
		
	// Check if we have correct owner
	$sql="select ad_owner from $ads_tbl where ad_id=$aAdID";
	$r=q($sql);
	$row=mysql_fetch_array($r);
	
	if ($row["ad_owner"]!=$aUserID)
		failMsg("Critical Error","You do not own this ad");

	$lTitle=strToDb($lTitle);
	$lRegion=strToDb($aRegion);
	$lDescr=strToDb($aDescr);
	
	if ($lRegion=="")
		$lRegion=0;
		
	$sql="update $ads_tbl set ";
	$sql.="ad_title='$lTitle',ad_description='$lDescr',ad_cat_id=$aCat,ad_region=$lRegion,ad_date_updated=". time();
	$sql.=",ad_precio=$aPrice, ad_moneda='$aMoneda'";
	$sql.=", ad_localidad_id=$aLocalidad";
	if($ProvinciaId!=null){
		$sql.=", ad_provincia=$ProvinciaId";
	}
	
	if ($aExpireAfterDays)
		$sql.=",ad_date_expire=$lExpireDate";
	if ($aSpecial)
		$sql.=",ad_is_special=$aSpecial";
	if ($aPremium)
		$sql.=",ad_is_premium=$aPremium";
		
	$sql.=" WHERE ad_id=$aAdID";	
	$res=q($sql);
	
	addToHistory(7,$aUserID,$aAdID,"");
	
	if ($aExtraFields)
	{
		updateSelected($aExtraFields,$aAdID,"");		
		
	}	
	
	if ($aNotifyAdmin==1)
	{
		// Notify administator that they have a new ad		
		$url = "http://" . $set_url . "/detail.php?id=$aAdID";
		$subject = formatString(LA_UPDATED_AD_INFO,array($aAdID,$aTitle,$aDescr,$url,getRemoteIp()));
		$body = formatString(LA_UPDATED_AD_INFORM,array($aAdID,$aTitle,$aDescr,$url,getRemoteIp()));
		
		if ($set_webmaster_address)
			sendEmail($set_webmaster_address,$set_webmaster_address,$subject,$body);
	}	
	
	// Decrease cat counter (removing one ad)
	categoryCounter($lOriginalCatid,2);
	// Increase Cat Counters
	categoryCounter($aCat,1);	
	
	return $aAdID;	
}

function getTables()
{	
	global $set_mysql_base;
	$res=q("show tables from `$set_mysql_base`");
	while ($row=mysql_fetch_array($res))
	{
		$lTableArray[]=$row[0];
		
	}
	return $lTableArray;
}

function checkIfExists($lArray,$aTableName)
{
	if (!empty($lArray))
	{
		foreach ($lArray as $lTable)
		{
			if ($aTableName==$lTable)
				return true;
			
		}
	}
	return false;	
}

function checkIfExistsField($lFields,$aTableName,$aField)
{
	
	if (!empty($lFields))
	{
		
		foreach ($lFields as $lField)
		{
			if (trim($aField)==trim($lField))
				return true;
			
		}
	}
	return false;	
}


function getFields($aTableName)
{	
	global $set_mysql_base;
	$res=q("show fields from $aTableName from `$set_mysql_base`");
	
	while ($row=mysql_fetch_array($res))
	{
		$lFieldArray[$i]["Field"]=$row["Field"];
		$lFieldArray[$i]["Type"]=$row["Type"];
		$lFieldArray[$i]["Extra"]=$row["extra"];
		$i++;
		
		
	}
	return $lFieldArray;
}

function getIndex($aTableName)
{
	global $set_mysql_base;
	$sql = "SHOW INDEX FROM $aTableName FROM `$set_mysql_base`";
	$res = mysql_query($sql);
	$row=mysql_fetch_array($res);
	return $row["Column_name"];
}

function getAllTables()
{	
	global $set_mysql_base;
	
	$res=q("show tables from `$set_mysql_base`");
	while ($row=mysql_fetch_array($res))
	{
		$resFields=q("show fields from `" . $row[0]  . "` from `$set_mysql_base`");
		while ($row_fields=mysql_fetch_array($resFields))
		{
			$lFieldArray[$i]["Table"]=$row[0];
			$lFieldArray[$i]["Field"]=$row_fields["Field"];
			$lFieldArray[$i]["Type"]=$row_fields["Type"];
			$lFieldArray[$i]["Extra"]=$row_fields["Extra"];
			$i++;
			
			
		}
		
		
	}
	return $lFieldArray;
}

function getBanner($aSection,$aCatIdList)
{	
}
 function mysql_draw_table($result, $null = '&nbsp;')
 {
     // Sanity check
     if (!is_resource($result) ||
         substr(get_resource_type($result), 0, 5) !== 'mysql') {
         return false;
     }
  
     $out = "<table>\n";
   
     // Table header
     $out .= "\t<tr>";
     for ($i = 0, $ii = mysql_num_fields($result); $i < $ii; $i++) {
         $out .= '<th>' . mysql_field_name($result, $i) . '</th>';
     }
     $out .= "</tr>\n";
   
     // Table content
     for ($i = 0, $ii = mysql_num_rows($result); $i < $ii; $i++) {
         $out .= "\t<tr>";
  
         $row = mysql_fetch_row($result);
         foreach ($row as $value) {
             // Display empty cells
             $value = (empty($value) && ($value != '0')) ?
                 $null :
                 htmlspecialchars($value);
  
             $out .= '<td>' . $value . '</td>';
         }
         $out .= "</tr>\n";
     }
   
     $out .= "</table>\n";
     echo $out;
 }

function CheckIfStillValidUser()
{
	global $usr_tbl,$set_table_prefix;

	$lUserId=$_SESSION["valid_user"];
	$lUserEmail=$_SESSION["user_email"];
	$lSql="select count(user_id) as num from $usr_tbl where user_id=$lUserId";
	$lSql.=" AND user_email='" . $lUserEmail . "'";
	$lRes=q($lSql);
	$lRow=mysql_fetch_array($lRes);
	if ($lRow["num"]<1)
	{
		@session_destroy();
		redirect("index.php");
	}
	
	
}

/**
DJ: Aca se levantan las opciones de los campos
*/
function getExtraForm()
{
	global $q_tbl;
	$lSql="select * from $q_tbl order by q_seq asc";
	$lRes=q($lSql);
	$i=0;
	$lStr="<?\n";
	define("LA_NOT_DEFINED","Not defined string");
	
	while ($row=mysql_fetch_array($lRes))
	{
		$lQuestion=$row["q_question"];
		$lCatDescr=$row["q_catdescr"];
		$lRegExpError=$row["q_reg_exp_errormsg"];
		
		
		//if ($lQuestion)
			//$lQuestion=constant($lQuestion);
		//if ($lCatDescr)
			//$lCatDescr=constant($lCatDescr);
		//if ($lRegExpError)
			//$lRegExpError=constant($lRegExpError);
			
		$lStr.="\$" . "lExtra[". $row["q_field"] . "]['q_field']='" . $row["q_field"] . "';\n";	
		$lStr.="\$" . "lExtra[". $row["q_field"] . "]['q_question']='" . $lQuestion . "';\n";
		$lStr.="\$" . "lExtra[". $row["q_field"] . "]['q_size']='" . $row["q_size"] . "';\n";
		$lStr.="\$" . "lExtra[". $row["q_field"] . "]['q_type']='" . $row["q_type"] . "';\n";
		$lStr.="\$" . "lExtra[". $row["q_field"] . "]['q_catdescr']='" . $lCatDescr . "';\n";
		$lStr.="\$" . "lExtra[". $row["q_field"] . "]['q_seq']='" . $row["q_seq"] . "';\n";
		$lStr.="\$" . "lExtra[". $row["q_field"] . "]['q_page']='" . $row["q_page"] . "';\n";
		$lStr.="\$" . "lExtra[". $row["q_field"] . "]['q_mand']='" . $row["q_mand"] . "';\n";
		$lStr.="\$" . "lExtra[". $row["q_field"] . "]['q_tpl']='" . $row["q_tpl"] . "';\n";
		$lStr.="\$" . "lExtra[". $row["q_field"] . "]['q_between']='" . $row["q_between"] . "';\n";
		$lStr.="\$" . "lExtra[". $row["q_field"] . "]['q_include_search']='" . $row["q_include_search"] . "';\n";
		$lStr.="\$" . "lExtra[". $row["q_field"] . "]['q_isurl']='" . $row["q_isurl"] . "';\n";
		$lStr.="\$" . "lExtra[". $row["q_field"] . "]['q_size_2']='" . $row["q_size_2"] . "';\n";
		$lStr.="\$" . "lExtra[". $row["q_field"] . "]['q_user_only']='" . $row["q_user_only"] . "';\n";
		$lStr.="\$" . "lExtra[". $row["q_field"] . "]['q_reg_exp']='" . $row["q_reg_exp"] . "';\n";
		$lStr.="\$" . "lExtra[". $row["q_field"] . "]['q_ad_list']='" . $row["q_ad_list"] . "';\n";
		$lStr.="\$" . "lExtra[". $row["q_field"] . "]['q_reg_exp_errormsg']='" . $lRegExpError . "';\n"; 
		$lStr.="\$" . "lExtra[". $row["q_field"] . "]['q_css_class']='" . $row["q_css_class"] . "';\n";
		
		$i++;
	}
	$lStr.="\n?>";
	return $lStr;
}


function getExtraOptionsForm()
{
	global $opt_tbl,$language,$set_multilang_cat;
	$lSql="select * from $opt_tbl order by opt_id asc";
	$lRes=q($lSql);
	$i=0;
	$lStr="<?\n";
	//define("LA_NOT_DEFINED","Not defined string");
	
	while ($row=mysql_fetch_array($lRes))
	{
		/*
		$lQuestion=$row["q_question"];
		$lCatDescr=$row["q_catdescr"];
		
		
		if ($lQuestion)
			$lQuestion=constant($lQuestion);
		if ($lCatDescr)
			$lCatDescr=constant($lCatDescr);
		*/
		
		$lStr.="\$" . "lExtraOptions[".$row["opt_belongto"]."][". $row["opt_id"] . "]['value']='" . $row["opt_id"] . "';\n";
		$lStr.="\$" . "lExtraOptions[".$row["opt_belongto"]."][". $row["opt_id"] . "]['text']='" . $row["opt_name"] . "';\n";
		$lStr.="\$" . "lExtraOptions[".$row["opt_belongto"]."][". $row["opt_id"] . "]['belongto']='" . $row["opt_belongto"] . "';\n";
		
		if ($set_multilang_cat) // TODO: Multi language options
		{
				// Here needs code to loop through all languages and get each $row(opt_fre), $row(opt_ger) and so on			
				// These options are cached.. so in addition, this must also be fetched on the end user side and then selected what opt_lang to use
				
				
				// Simple implementation.. not good, but it gets the default option langauge...
				$lang_cat="opt_" . $language;
				
				if ($row["$lang_cat"]!="")
					$lStr.="\$" . "lExtraOptions[".$row["opt_belongto"]."][". $row["opt_id"] . "]['text']='" . $row["$lang_cat"] . "';\n";
				
				
		}
		
		
		
		$i++;
	}
	$lStr.="\n?>";
	return $lStr;
}


function getExtra()
{
	global $set_path,$set_cache_time;
	$cache_active = true;  

	$result = acmeCache::fetch('getExtraForm', $set_cache_time); // 10 seconds 
	if(!$result)
		acmeCache::save('getExtraForm', getExtraForm()); 

	include $set_path . "/admin/config/cache/getExtraForm.cache";
	
	return $lExtra;
}

function getExtraOptions()
{
	global $set_path,$set_cache_time;
	$cache_active = true;  

	$result = acmeCache::fetch('getExtraOptionsForm', $set_cache_time); // 10 seconds 
	if(!$result)
		acmeCache::save('getExtraOptionsForm', getExtraOptionsForm()); 

	include $set_path . "/admin/config/cache/getExtraOptionsForm.cache";
	
	return $lExtraOptions;
}

function getExtraAllOptions()
{
	global $set_path,$set_cache_time;
	$cache_active = true;  

	$result = acmeCache::fetch('getExtraOptionById', $set_cache_time); // 10 seconds 
	if(!$result)
		acmeCache::save('getExtraOptionById', getExtraOptionsForm()); 

	include $set_path . "/admin/config/cache/getExtraOptionById.cache";
	
	return $lExtraOptions;
}

function getExtraWithOptions($aLanguage=null)
{
	global $opt_tbl,$set_multilang_opt;
	
	if ($set_multilang_opt)
	{
		$lLangSupportedArray=split(",",$set_multilang_opt);
		if (in_array($aLanguage,$lLangSupportedArray))
			$lFieldName="opt_" . $aLanguage;
	}
	if (!$lFieldName)
		$lFieldName="opt_name";
	
	$lQuestions=getExtra();	
	if (!$aLanguage)
		$lOptions=getExtraOptions();
	
	if (is_array($lQuestions))
	{
		foreach($lQuestions as $lItem)
		{
			$lFieldNb=$lItem["q_field"];
			
			//print_r($lQuestions);
			$lOpt="";
			if ($aLanguage) // If we have set language from item.php, connect to db and get options with correct language
			{
				$lSql="select opt_id,opt_belongto,$lFieldName as value from $opt_tbl where opt_belongto=$lFieldNb";	
				$lRes=q($lSql);
				$i=1;
				while ($lRowOptFetch=mysql_fetch_array($lRes))
				{
					$lOpt[$i]["belongto"]=$lRowOptFetch["opt_belongto"];
					$lOpt[$i]["text"]=$lRowOptFetch["value"];
					$lOpt[$i]["value"]=$lRowOptFetch["opt_id"];
					
					$i++;
				}
				$lQuestions[$lFieldNb]["options"]=$lOpt;
			}
			else 
			{
				$lQuestions[$lFieldNb]["options"]=$lOptions[$lFieldNb];
			}
			
		}
	}

	return $lQuestions;
}

function getExtraByValue()
{
	$lQuestions=getExtra();	
	$lOptions=getExtraOptions();
	
}

function getExtraFiltered($aTemplate,$aAd,$aUser,$aLanguage=null)
{
	$lFields=getExtraWithOptions($aLanguage);
	

	global $sel_tbl,$lNewFilteredArray;
	
	if (getParam("update_rq","")==1 && getParam("submit","")!="") 
	{
		if ($aAd) // We need to remove initial data (important for checkbox)
			q("delete from $sel_tbl WHERE sel_option_ad=$aAd");
	}
	
	if ($aAd || $aUser)
	{
		if ($aAd)
			$lSql="select * from $sel_tbl where sel_option_ad IN ($aAd)";
		else // User
			$lSql="select * from $sel_tbl where sel_option_user IN ($aUser)";
		$lRes=q($lSql);
		$t=0;
		while ($lRow=mysql_fetch_array($lRes))
		{
			$lArray[$lRow["sel_option_field"]][$t]=$lRow["sel_option_id"];
			if ($lRow["sel_option_decimal"]!="")
				$lArray[$lRow["sel_option_field"]]["sel_option_text"]=$lRow["sel_option_decimal"];
			else
				$lArray[$lRow["sel_option_field"]]["sel_option_text"]=$lRow["sel_option_text"];
			//echo $lArray[$lRow["sel_option_field"]][$t] . "<br>";
			//JMR: agregue esta linea para los combos especiales: J
			if ($lRow["sel_option_text"]=="marca")
			{
				$lArray[$lRow["sel_option_field"]]["sel_option_text"]=$lRow["sel_option_id"];
			}
			//END JMR:
			$t++;
		}
	}
	
	if (is_array($lFields))
	{	
		foreach($lFields as $lItem) // Loop through all fields with options, get data value
		{
			/*
			If this question is a User field and aAd>0, then lSkip=1.
			If this question is a Ad field and aUser>0, then lSkip=1.
			I
			*/
			
			$lSkip=0;
			$lFieldNb=$lItem["q_field"];
			
			if ($aAd)
			{
				if ($lFields[$lFieldNb]["q_user_only"]==1) // Hide User fields on ad change
					$lSkip=1;
			}
			if ($aUser)
			{
				if ($lFields[$lFieldNb]["q_user_only"]!=1) // Only show User fields that are user fields
					$lSkip=1;
			}
			if (!$aUser && !$aAd && $lFields[$lFieldNb]["q_user_only"]==1) // If Search page, don�t display user fields
				$lSkip=1;
						
			if (!$lSkip)
			{
				if ($lFields[$lFieldNb]["q_tpl"]==$aTemplate || $lFields[$lFieldNb]["q_tpl"]==1)
				{
					$lNewFilteredArray[$lFieldNb]=$lFields[$lFieldNb];					
					$lFieldName="e_" . $lFieldNb; 
					
					$lJoinedInputArray=array_merge($_POST,$_GET);
					
					if ($lJoinedInputArray["$lFieldName"]!="" || is_array($lJoinedInputArray["$lFieldName"]))
					{						
						updateArraySetSelected($lJoinedInputArray["$lFieldName"],$lFieldNb);
					}
					else if ($aAd || $aUser)
					{
						updateArraySetSelected($lArray[$lFieldNb],$lFieldNb);						
					}
					
				}
			}
		
		}
	}
	return $lNewFilteredArray;
}

/***
This function decides what to show in the input form during new ad input
***/
function updateArraySetSelected($aArrayOrSingleValueSelected,$aFieldNb)
{
	global $lNewFilteredArray,$set_debug;
	if (is_array($aArrayOrSingleValueSelected))
	{			
		if ($lNewFilteredArray[$aFieldNb]["q_type"]=="s" || $lNewFilteredArray[$aFieldNb]["q_type"]=="c" || $lNewFilteredArray[$aFieldNb]["q_type"]=="r")
		{
			foreach ($aArrayOrSingleValueSelected as $lItem)
			{
				if (!empty($lItem))
				{
				if (is_array($lNewFilteredArray))
				{
					foreach ($lNewFilteredArray as $value) 
					{
							if (is_array($value))
							{
								if (is_array($value["options"]))
								{
									foreach ($value["options"] as $key => $value)
									{
										
											if ($key=="")
												$key=0;
											
											if ($value["value"]==$lItem)
												$lNewFilteredArray["$aFieldNb"]["options"][$key]["selected_value"]=$lItem;
												
									}
								}
							}
					}					
				}
				}	
				
			}
		}
		else // Single value sent in
		{
			$lNewFilteredArray["$aFieldNb"]["q_value"]=htmlspecialchars($aArrayOrSingleValueSelected["sel_option_text"],ENT_QUOTES);
			if ($set_debug)
				echo "<p>Field $aFieldNb is text. Content extracted from array</p>";
		}
	}
	else if ($aArrayOrSingleValueSelected !="") // Single single value sent in
	{	
		if ($lNewFilteredArray[$aFieldNb]["q_type"]=="s" || $lNewFilteredArray[$aFieldNb]["q_type"]=="c" || $lNewFilteredArray[$aFieldNb]["q_type"]=="r")
		{
			if (is_array($lNewFilteredArray[$aFieldNb]["options"]))
			{
				foreach ($lNewFilteredArray[$aFieldNb]["options"] as $key => $value)
				{
					
					if ($key=="")
						$key=0;
							
					if ($lNewFilteredArray[$aFieldNb]["options"][$key]["value"]==$aArrayOrSingleValueSelected)
						$lNewFilteredArray[$aFieldNb]["options"][$key]["selected_value"]=$aArrayOrSingleValueSelected;
								
				}
				
			}
			
		}
		else 
		{	
			$lNewFilteredArray["$aFieldNb"]["q_value"]=strEnc(cleanInput($aArrayOrSingleValueSelected));	
			if ($set_debug)
				echo "<p>Field $aFieldNb is text. Content from single value field</p>";
		}
	}	
}

/* Extra fields: List display and detailed page */
function getFieldArray($aAdList,$aUserList,$aDelimiter,$aLanguage=null)
{
	global $sel_tbl,$opt_tbl,$q_tbl,$set_multilang_opt;
			
	//$lExtraFieldValues="select sel_option_id,sel_option_ad,sel_option_user,sel_option_field,sel_option_text from $sel_tbl,$q_tbl where sel_option_field=q_field AND sel_option_ad IN ($aAdList) OR sel_option_user IN ($aUserList) order by q_seq asc";
	$lExtraFieldValues="select sel_option_id,sel_option_ad,sel_option_user,sel_option_field,sel_option_text,sel_option_decimal from $sel_tbl ";
	if ($aAdList && $aUserList)
		$lExtraFieldValues.="where sel_option_ad IN ($aAdList) OR sel_option_user IN ($aUserList)";
	else if ($aAdList)
		$lExtraFieldValues.="where sel_option_ad IN ($aAdList)";
	else if ($aUserList)
		$lExtraFieldValues.="where sel_option_user IN ($aUserList)";
	else 
		return "";
		
	$lExtraFieldValues.=" order by sel_sort_nb asc";//q_seq asc,
	$lExtraRes=q($lExtraFieldValues);
	//logMsg("JMR obteniendo Los valores del AD: ","query: ".$lExtraFieldValues);
	$lOptions=getExtraWithOptions($aLanguage);
	
	while ($lExtraRow=mysql_fetch_array($lExtraRes))
	{
		
		$lExtraAdId=$lExtraRow["sel_option_ad"];
		$lExtraUserId=$lExtraRow["sel_option_user"];
		$lExtraFieldName=e_.$lExtraRow["sel_option_field"];
		$lExtraFieldId=$lExtraRow["sel_option_field"];
		$lExtraSelectedId=$lExtraRow["sel_option_id"];
		if ($lExtraRow["sel_option_decimal"]!="")
			$lExtraSelectedText=$lExtraRow["sel_option_decimal"];
		else
			$lExtraSelectedText=$lExtraRow["sel_option_text"];
		
		if ($lExtraAdId)
		{
			$lAdOrUserIdentifier=$lExtraAdId;
			$lFieldAddOn="ad";
		}
		else if ($lExtraUserId)
		{
			$lAdOrUserIdentifier=$lExtraUserId;
			$lFieldAddOn="user";
		}
		
		$lItemValue="";
		if (!empty($lExtraSelectedId)) // Is item in option list
		{
			if (!empty($_SESSION["la"]))
				if ($_SESSION["la"]!="eng")
				{
					if ($lOptions[$lExtraFieldId]["options"][$lExtraSelectedId]["text_" . $_SESSION["la"]]!="")
						$lCurrentLangItem="text_" . $_SESSION["la"];
				}
			
			if ($lCurrentLangItem=="")	
				$lCurrentLangItem="text";

			if ($set_multilang_opt)
			{
				$lLangSupportedArray=split(",",$set_multilang_opt);
				if (in_array($aLanguage,$lLangSupportedArray))
					$lFieldName="opt_" . $aLanguage;
			}
			
			if (!$lFieldName)
				$lFieldName="opt_name";			
			if((empty($lExtraSelectedText) || $lExtraSelectedText!="marca") && ($lExtraSelectedId!=-1))
			{
				$lSql="select $lFieldName as value from $opt_tbl where opt_id=$lExtraSelectedId";	
				$lRes=q($lSql);
				$lRowOptFetch=mysql_fetch_array($lRes);
				$lItemValue=$lRowOptFetch["value"];
				
			}else
			{
				if($lExtraSelectedId!=-1){
				
					//logMsg("JMR: Obteniendo Marca 01","$lExtraSelectedId");
					
						$query=("SELECT marca from marca where id=".$lExtraSelectedId);				
						$result=q($query);
						$array=mysql_fetch_array($result);						
						$lItemValue=$array["marca"];
				}else {
						$query=("SELECT mv_marca_str from mvial_ad_extra_options where mv_ad_id=".$lExtraAdId);
						//logMsg("JMR: Obteniendo Marca 02","$query");				
						$result=q($query);
						$array=mysql_fetch_array($result);						
						$lItemValue=$array["mv_marca_str"];						
				}
			}
			//$lItemValue=$lOptions[$lExtraFieldId]["options"][$lExtraSelectedId]["$lCurrentLangItem"];
			//	echo $lExtraSelectedId;
		}
		elseif (!empty($lExtraSelectedText))
		{
			$lItemValue=$lExtraSelectedText;
		}
		
		if (!empty($fExtraArray["$lFieldAddOn"][$lAdOrUserIdentifier][$lExtraFieldName]["value"]))
			$lItemValue=$fExtraArray["$lFieldAddOn"][$lAdOrUserIdentifier][$lExtraFieldName]["value"] . "$aDelimiter " .$lItemValue;	
			
		$fExtraArray["$lFieldAddOn"][$lAdOrUserIdentifier][$lExtraFieldName]["value"]=$lItemValue;
		$fExtraArray["$lFieldAddOn"][$lAdOrUserIdentifier][$lExtraFieldName]["field"]=$lExtraFieldName;
		$fExtraArray["$lFieldAddOn"][$lAdOrUserIdentifier][$lExtraFieldName]["description"]=$lOptions[$lExtraFieldId]["q_catdescr"];
		$fExtraArray["$lFieldAddOn"][$lAdOrUserIdentifier][$lExtraFieldName]["question"]=$lOptions[$lExtraFieldId]["q_question"];
		$fExtraArray["$lFieldAddOn"][$lAdOrUserIdentifier][$lExtraFieldName]["seq"]=$lOptions[$lExtraFieldId]["q_seq"];
		$fExtraArray["$lFieldAddOn"][$lAdOrUserIdentifier][$lExtraFieldName]["type"]=$lOptions[$lExtraFieldId]["q_type"];
		$fExtraArray["$lFieldAddOn"][$lAdOrUserIdentifier][$lExtraFieldName]["islink"]=$lOptions[$lExtraFieldId]["q_isurl"];			
	
	}
 	return $fExtraArray;
}

/* Function is responsible for returning data to be put in DB and possible error messages */
function ExtraFieldsInputOperations($lFieldArray)
{	
	$lQuestionArray=getExtra();
	
	foreach($lFieldArray as $lItem)
	{
		//$lInsertArray[$j]["sel_option_id"]="";
		// Field number (also called question number)
		$lFieldNb=$lItem["q_field"];
		$lFieldName="e_" . $lItem["q_field"];
		$lFieldSeq=$lItem["q_seq"];
		
		
		if ($lItem["q_type"]!="e" && $lItem["q_type"]!="t" && $lItem["q_type"]!="j" && $lItem["q_type"]!="a" && $lItem["q_type"]!="d" && $lItem["q_type"]!="p")
		{
			// Loop through each option in order to find out values to insert into db
			if (count($lItem["options"])>0)
			{				
				foreach ($lItem["options"] as $lOptions)
				{   
					if ($lOptions["selected_value"] !=null)
					{
						
						$lInsertArray[$j]["sel_option_id"]=$lOptions["selected_value"];
						$lInsertArray[$j]["sel_option_field"]=$lFieldNb;
						$lInsertArray[$j]["sel_option_type"]="";
						$lInsertArray[$j]["sel_option_seq"]=$lFieldSeq;
						$j++;
						
					}
					
				}
			}
		}
		else if($lItem["q_type"]=="j" || $lItem["q_type"]=="a")
		{			
			if($_POST["otraMarca"]==""){
				$lInsertArray[$j]["sel_option_field"]=$lFieldNb;			
				$lInsertArray[$j]["sel_option_seq"]=$lFieldSeq;
				$lInsertArray[$j]["sel_option_id"]=$_POST["$lFieldName"];
				$lInsertArray[$j]["sel_option_text"]="marca";
			
			}else{
				$lInsertArray[$j]["sel_option_field"]=$lFieldNb;			
				$lInsertArray[$j]["sel_option_seq"]=$lFieldSeq;
				$lInsertArray[$j]["sel_option_id"]=-1; //-1 indica que se dió de alta 
				$lInsertArray[$j]["sel_option_text"]=$_POST["otraMarca"];
				
			}
			/*//Descomentar para que se guarde la marca en el campo Texto.
				if($lInsertArray[$j]["sel_option_id"]!=null && $lInsertArray[$j]["sel_option_id"]!="")
				{	$query=("SELECT marca from marca where id=".$lInsertArray[$j]["sel_option_id"]);				
					$result=q($query);
					$array=mysql_fetch_array($result);			
					//logMsg("JMR: marca elegida ",$array["marca"]);
					$lInsertArray[$j]["sel_option_text"]=$array["marca"];
				}
			*/
			$j++;						
		}
		else if ($lItem["q_type"]=="t" || $lItem["q_type"]=="d" || $lItem["q_type"]=="c")
		{
			$lInsertArray[$j]["sel_option_field"]=$lFieldNb;
			$lInsertArray[$j]["sel_option_text"]=$_POST["$lFieldName"];
			$lInsertArray[$j]["sel_option_seq"]=$lFieldSeq;
			$j++;
		}
		else if ($lItem["q_type"]=="p")
		{
			$lInsertArray[$j]["sel_option_field"]=$lFieldNb;
			$lInsertArray[$j]["sel_option_decimal"]=$_POST["$lFieldName"];
			$lInsertArray[$j]["sel_option_seq"]=$lFieldSeq;
			$j++;
		}
		
	
		if (getParam("submit",""))
		{
			if ($_POST["$lFieldName"] !=null)
				$lPostedValue=$_POST["$lFieldName"];
			else 
				$lPostedValue="";
				
			if ($lItem["q_mand"]==1 && $lPostedValue=="")
				$errorMsg.= "<li>".LA_YOU_MUST ." <b>" . $lItem["q_question"] . "</b></li>";
				
			if ($lQuestionArray["$lFieldNb"]["q_isurl"]==1)
			{
				if (!ereg("^http://",$_POST["$lFieldName"]) && !empty($_POST["$lFieldName"]))
					$errorMsg.= "<li>".LA_YOU_MUST ." <b>" . constant($lItem["q_question"]) . "</b>.&nbsp;" .LA_YOU_MUST_URL. "</li>";
			}
			
			if (!empty($lQuestionArray["$lFieldNb"]["q_reg_exp"]))
			{
						if (!preg_match($lQuestionArray["$lFieldNb"]["q_reg_exp"],$_POST["$lFieldName"]))
					{
						if ($lQuestionArray["$lFieldNb"]["q_reg_exp_errormsg"])
							$errorMsg.="<li>".constant($lQuestionArray["$lFieldNb"]["q_reg_exp_errormsg"]) . "</li>";
						elseif ($lQuestionArray["$lFieldNb"]["q_question"])
							$errorMsg.="<li>".constant($lQuestionArray["$lFieldNb"]["q_question"]) . "</li>";
					}
			}		
				
		}

	}
	
	$lReturnResultArray[0]=$lInsertArray;
	$lReturnResultArray[1]=$errorMsg;
	return $lReturnResultArray; // Return data to be inserted into db and possible error messages
}


function doAuthphpBB($aUsername,$aPassword)
{
	global $usr_tbl,$set_phpbb_activate,$set_phpbb_table,$set_phpbb_db_name,$set_phpbb_db_user,$set_phpbb_db_pass,$set_phpbb_db_host;
	
	// Secure input values
	$aUsername=strToDb($aUsername);
	$aPassword=strToDb($aPassword);
	
	$conn_id= @mysql_connect("$set_phpbb_db_host","$set_phpbb_db_user","$set_phpbb_db_pass");
	if (!$conn_id)
		die('<br /><b>phpBB Connection Failed!</b><br />Please check your PHPBB database details in settings, they are wrong.
		If you deactivate phpBB, this error will go away.');		
	$res_pointer=mysql_select_db("$set_phpbb_db_name",$conn_id); 
		
	$sql = "select * from $set_phpbb_table where user_email= '$aUsername' AND user_password=md5('" . $aPassword . "')";
	$res = mysql_query($sql,$conn_id);
	$num = mysql_num_rows($res);
	$row=mysql_fetch_array($res);
	
	if ($num>0)
	{
		
		$lEmail=$row["user_email"];
		$lName=$row["username"];
		$lphpBBUserId=$row["user_id"];
		
		$lRes=specialq("select * from $usr_tbl where user_email = '$aUsername'");
		if (mysql_num_rows($lRes)<1)
		{
			$lUserId=createUser($lEmail,"","$lName",1,0,"","");
			if ($lUserId>0)
				specialq("update $usr_tbl set user_pass_md5=md5('$aPassword') where user_id=$lUserId");
		}
		else 
			return false;
	}
	if ($num>0)
	{
		$_SESSION["phpbb_user_id"] = $lphpBBUserId;
		$_SESSION["sid"] = $lphpBBUserId;
		$_SESSION["session_logged_in"]=1;
		$_SESSION["session_user_id"]=$lphpBBUserId;
		$_SESSION["user_password"]=md5($aPassword);
		$_SESSION["user_active"]=1;
		
		return true;	
	}	
	return false;	
}

function makeUTF8($str,$encoding = "") {
  if ($str !== "") {
    if (empty($encoding) && isUTF8($str))
      $encoding = "UTF-8";
    if (empty($encoding))
      $encoding = mb_detect_encoding($str,'UTF-8, ISO-8859-1');
    if (empty($encoding))
      $encoding = "ISO-8859-1"; //  if charset can't be detected, default to ISO-8859-1
    return $encoding == "UTF-8" ? $str : @mb_convert_encoding($str,"UTF-8",$encoding);
    }
  }
function isUTF8($str) {
   return preg_match('%^(?:
         [\x09\x0A\x0D\x20-\x7E]           // ASCII
       | [\xC2-\xDF][\x80-\xBF]            // non-overlong 2-byte
       | \xE0[\xA0-\xBF][\x80-\xBF]        // excluding overlongs
       | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} // straight 3-byte
       | \xED[\x80-\x9F][\x80-\xBF]        // excluding surrogates
       | \xF0[\x90-\xBF][\x80-\xBF]{2}     // planes 1-3
       | [\xF1-\xF3][\x80-\xBF]{3}         // planes 4-15
       | \xF4[\x80-\x8F][\x80-\xBF]{2}     // plane 16
   )*$%xs', $str);
  }
  
function quote_smart($value) {
   if(is_array($value)) {
       if(get_magic_quotes_gpc()) {
           $value=array_map("stripslashes",$value);
           }
       if(!array_map("is_number",$value)) {
           $value=array_map("mysql_real_escape_string",$value);
           }
       }
   else {
       if(get_magic_quotes_gpc()) {
           $value=stripslashes($value);
           }
       if(!is_numeric($value)) {
           $value=mysql_real_escape_string($value);
           }
       }
   return $value;
   } 
function sEnc($aValue) {
	$lValue=htmlentities($new_name,ENT_QUOTES);
	return($lValue);
}

function sDec($aValue) {
	$lValue=unhtmlentities($aValue);
  return($lValue);
}

function linkDetail($aId)
{
	global $set_rewrite,$set_link_detail;
	
	if ($set_rewrite=="1")
		return ereg_replace("\(n\)","$aId","$set_link_detail");
	else 
		//return "detail.php?id=" . $aId;
		$query = "select * from mvial_ad where ad_id = " . $aId;
		$sql=mysql_query($query);
		while($rg=mysql_fetch_object($sql)) {
			$link_provincia_id = $rg->ad_provincia;
			$link_provincia = busca_existencia_dato("provincia","id",$link_provincia_id,"1",1,"nombre");
			$link_provincia = strtolower($link_provincia);
			$link_title = $rg->ad_title;
			$link_cat_id = $rg->ad_cat_id;
		}

		$query = "select * from mvial_category where cat_id = " . $link_cat_id;
		$sql=mysql_query($query);
		while($rg=mysql_fetch_object($sql)) {
			$link_subcategoria_id = $rg->cat_id;
			$link_subcategoria_nombre = $rg->cat_name;
			$link_categoria_id = $rg->cat_fatherid;
		}

		$query = "select * from mvial_category where cat_id = " . $link_categoria_id;
		$sql=mysql_query($query);
		while($rg=mysql_fetch_object($sql)) {
			$link_categoria_nombre = strtolower($rg->cat_name);
			$link_categoria_nombre = str_replace("venta ", "", $link_categoria_nombre);			
			$link_categoria_nombre = str_replace("alquiler ", "", $link_categoria_nombre);			
			$link_categoria_operacion = $rg->cat_fatherid;
		}

		$query = "select * from mvial_category where cat_id = " . $link_categoria_operacion;
		$sql=mysql_query($query);
		while($rg=mysql_fetch_object($sql)) {
			$link_operacion_nombre = strtolower($rg->cat_name);
		}

		if(strtolower($link_operacion_nombre) == "venta"){
			$usado = 0;
			$link_item_adicional = "";
			$query = "select * from mvial_selected where sel_option_ad = " . $aId . " and sel_option_id in (select opt_id from mvial_options where opt_name = 'Usado')";
			$sql=mysql_query($query);
			while($rg=mysql_fetch_object($sql)) {
				$usado = $rg->sel_id;
				$link_item_adicional = "usad";
			}
			$nuevo = 0;
			$query = "select * from mvial_selected where sel_option_ad = " . $aId . " and sel_option_id in (select opt_id from mvial_options where opt_name = 'Nuevo')";
			$sql=mysql_query($query);
			while($rg=mysql_fetch_object($sql)) {
				$nuevo = $rg->sel_id;
				$link_item_adicional = "nuev";
			}
		
			if($link_item_adicional != ""){
				include("categorias_femeninas.php");
				if (in_array($link_subcategoria_id, $cat_femenina)) {
					$link_item_adicional .= "as/";
				} else {
					$link_item_adicional .= "os/";
				}
			}

		}
		

		$link_item = "/" . guiones($link_categoria_nombre) . "/" . guiones($link_subcategoria_nombre) . "/" . $link_operacion_nombre . "/" . $link_item_adicional . $aId ."-" . guiones($link_title) . "-" . guiones($link_provincia);
		return $link_item;

}
function linkDetailClean($aId)
{
        global $set_rewrite,$set_link_detail;

        if ($set_rewrite=="1")
                return ereg_replace("\(n\)","$aId","$set_link_detail");
        else
                return "detail.php?id=" . $aId;
}


function linkCat($aId)
{
	global $set_rewrite,$set_link_cat;
	
	if ($set_rewrite=="1")
		return ereg_replace("\(n\)","$aId","$set_link_cat");
	else 
		return "index.php?catid=" . $aId;
}

function linkUser($aId)
{
	global $set_rewrite,$set_link_user;
	
	if ($set_rewrite=="1")
		return ereg_replace("\(n\)","$aId","$set_link_user");
	else 
		return "user_info.php?user_id=" . $aId;
}

 function build_cat_tree($parent_id,$tree_name,$tree_type) {
        global $cat_tbl,$set_multilang_cat,$set_url,$lCurrentSubscribedArray;
        
        $sql = "SELECT * FROM $cat_tbl WHERE cat_fatherid='$parent_id' ORDER BY cat_name";
        $result = q($sql);
        if (mysql_num_rows($result) == 0) return;
        while ($row = mysql_fetch_assoc($result)) {
                $cid = $row["cat_id"];
                $allowads = $row["cat_allow_ads"];
                $num_ads = $row["cat_total"];
                $catname=addslashes($row["cat_name"]);
                if (!empty($_SESSION["la"]) AND $set_multilang_cat)
                {
                        $lang_cat = "lang_" . $_SESSION["la"];
                        if (!empty($row["$lang_cat"]))
                                  $catname = addslashes($row["$lang_cat"]);
                }
                $cat_image = ($row["cat_image"]!="default.gif" && $row["cat_image"]!="blank.gif" && $row["cat_image"])?"http://".$set_url."/catimages/".$row["cat_image"]:"";
                $cat_description=($row["cat_description"])?addslashes($row["cat_description"]):$catname;
                if ($parent_id=="")
        			$parent_id="0";
        		
        		if ($tree_type==1) // If Add ad page
        		{
	        		if ($allowads) {$lString.= $tree_name.".add($cid,$parent_id,'".$catname." *','payment_options.php?catid=".$cid."','".$cat_description." *','','$cat_image','$cat_image');\r\n";}
	                else {$lString.=$tree_name.".add($cid,$parent_id,'".$catname."','#','".$cat_description."','','$cat_image','$cat_image');\r\n";}	
        		}
        		else if ($tree_type==3) // Notify new ads page
        		{
        			 if (in_array($cid,$lCurrentSubscribedArray))
	                	$lString.= $tree_name.".add($cid,$parent_id,'</a><input type=checkbox name=catid_rem[] value=\"$cid\" checked> <a href=\"index.php?catid=".$cid."\" target=_new>".$catname."','index.php?catid=".$cid."','','_new','$cat_image','$cat_image');\r\n";
	                else
	                {
	                	$lString.= $tree_name.".add($cid,$parent_id,'</a><input type=checkbox name=catid_rem[] value=\"$cid\"";
	                	if (!$allowads)
	                		$lString.=" disabled";
	                	$lString.=" />  <a href=\"index.php?catid=".$cid."\" target=_new>".$catname."','index.php?catid=".$cid."','','_new','$cat_image','$cat_image');\r\n";
	                }
				}
        		$lString.=build_cat_tree($cid,$tree_name,$tree_type);
        }
        mysql_free_result($result);
        return $lString;
 }
 
 /**
 Sin imagenes
 */
 function build_cat_tree2($parent_id,$tree_name,$tree_type) {
        global $cat_tbl,$set_multilang_cat,$set_url,$lCurrentSubscribedArray;
        
        $sql = "SELECT * FROM $cat_tbl WHERE cat_fatherid='$parent_id' ORDER BY cat_name";
        $result = q($sql);
        if (mysql_num_rows($result) == 0) return;
        while ($row = mysql_fetch_assoc($result)) {
                $cid = $row["cat_id"];
                $allowads = $row["cat_allow_ads"];
                $num_ads = $row["cat_total"];
                $catname=addslashes($row["cat_name"]);
                if (!empty($_SESSION["la"]) AND $set_multilang_cat)
                {
                        $lang_cat = "lang_" . $_SESSION["la"];
                        if (!empty($row["$lang_cat"]))
                                  $catname = addslashes($row["$lang_cat"]);
                }
                $cat_image = ($row["cat_image"]!="default.gif" && $row["cat_image"]!="blank.gif" && $row["cat_image"])?"http://".$set_url."/catimages/".$row["cat_image"]:"";
				$cat_image = "";
                $cat_description=($row["cat_description"])?addslashes($row["cat_description"]):$catname;
                if ($parent_id=="")
        			$parent_id="0";
        		
        		if ($tree_type==1) // If Add ad page
        		{
	        		if ($allowads) {$lString.= $tree_name.".add($cid,$parent_id,'".$catname." *','payment_options.php?catid=".$cid."','".$cat_description." *','','$cat_image','$cat_image');\r\n";}
	                else {$lString.=$tree_name.".add($cid,$parent_id,'".$catname."','#','".$cat_description."','','$cat_image','$cat_image');\r\n";}	
        		}
        		else if ($tree_type==3) // Notify new ads page
        		{
        			 if (in_array($cid,$lCurrentSubscribedArray))
	                	$lString.= $tree_name.".add($cid,$parent_id,'</a><input type=checkbox name=catid_rem[] value=\"$cid\" checked> <a href=\"index.php?catid=".$cid."\" target=_new>".$catname."','index.php?catid=".$cid."','','_new','$cat_image','$cat_image');\r\n";
	                else
	                {
	                	$lString.= $tree_name.".add($cid,$parent_id,'</a><input type=checkbox name=catid_rem[] value=\"$cid\"";
	                	if (!$allowads)
	                		$lString.=" disabled";
	                	$lString.=" />  <a href=\"index.php?catid=".$cid."\" target=_new>".$catname."','index.php?catid=".$cid."','','_new','$cat_image','$cat_image');\r\n";
	                }
				}
        		$lString.=build_cat_tree($cid,$tree_name,$tree_type);
        }
        mysql_free_result($result);
        return $lString;
 } 
 
 
 function getRegionsForOneLevel($aFatherId,$aSelected,$aAddOn)
{
	global $reg_tbl;
	
	if ($aFatherId=="")
		$aFatherId=0;
	
	$lSql = "select reg_id, reg_name, reg_father from $reg_tbl where reg_father=$aFatherId order by reg_name";
	$lRes=q($lSql);
	
	while ($lRow=mysql_fetch_array($lRes))
	{
		$lOptions.="<option value='" . $lRow["reg_id"] . "$aAddOn'";
		if ($lRow["reg_id"]==$aSelected)
			$lOptions.=" selected";
		$lOptions.=">".strEnc($lRow["reg_name"])."</option>";
		
	}
	return $lOptions;
}
function getRegionTree($parent, $level, $lSelected)
{
	global $reg_tbl;
	
	$parentsql = q("select reg_id, reg_name, reg_father from $reg_tbl where reg_father=$parent order by reg_pri,reg_name");
	if (!mysql_num_rows($parentsql))
	{	return; }
	else
	{
		while($branch = mysql_fetch_row($parentsql))
		{
			$echo_this = "<option ";
			if ($branch[0]==$lSelected)
				$echo_this.=" selected";
			$echo_this.=" value=$branch[0]>";
				for ($x=1; $x<=$level; $x++)
				{
				$echo_this .=  "&nbsp;&nbsp;&nbsp;";
				}

			$echo_this.="".strEnc($branch[1]) ."</option>";

			$lList.=$echo_this;

			$rename_level = $level;
			$lList.=getRegionTree($branch[0], ++$rename_level,$lSelected);
			}
		}
		
		return $lList;
}

function getSubRegions($parent, $level)
{
	global $reg_tbl;
	
	$parentsql = q("select reg_id,reg_father from $reg_tbl where reg_father=$parent order by reg_pri,reg_name");
	if (!mysql_num_rows($parentsql))
	{	return; }
	else
	{
		while($branch = mysql_fetch_row($parentsql))
		{
			$lList.=$branch[0] . ",";
			$rename_level = $level;
			$lList.=getSubRegions($branch[0], ++$rename_level);
			}
		}
		return $lList;
}


function getLevelRegion($aRegionId,$lLevelArray)
{
	global $reg_tbl,$k;
	$lSql="select reg_id,reg_father,reg_name from $reg_tbl where reg_id=". $aRegionId;
	$lResRegion=q($lSql);
	$k++;
	while ($lRowReg=mysql_fetch_array($lResRegion))
	{
		
		$lLevelArray[$k]["reg_id"]=$lRowReg["reg_id"];
		$lLevelArray[$k]["reg_father"]=$lRowReg["reg_father"];
		$lLevelArray[$k]["reg_name"]=strEnc($lRowReg["reg_name"]);
		
		$lLevelArray=getLevelRegion($lRowReg["reg_father"],$lLevelArray);
		
	}
	
	return $lLevelArray;
}

function getLangSupported($aFolder="admin/language_src/")
{
	$dir = opendir("$aFolder");
	
	while ($file = readdir($dir))
  	{
		if ($file <> "." AND $file <> ".." AND !ereg("user",$file))
        {
		  	$file = substr($file,0,3); 
		  	$array[] = $file;
		}
  	}
  	closedir($dir);
	return $array;
}


function makeLineBreaksFromCRLF($string) {

      $sDefinesRegExp = '/\015\012|\015|\012/';
      $sDefinesReplace = '<br />';

       return(preg_replace($sDefinesRegExp, $sDefinesReplace, $string));

}

function getConstantAndValues($sFileName) {

	$sDefinesRegExp = '/^\s*DEFINE\s*\(\s*(\'|")(\w+)\1\s*,\s*(\'|")(.*?)(?<!\\\\)\3\s*\)/im';
	$aConstantAndValue = array();

	if (file_exists($sFileName) && (is_file($sFileName))) {
		$sFile = file_get_contents($sFileName);

		preg_match_all($sDefinesRegExp, $sFile, $aConstantAndValueTemp);
		foreach ($aConstantAndValueTemp[2] as $key => $value) {
			$aConstantAndValue[$value] = unhtmlentities(($aConstantAndValueTemp[4][$key]));
		}
	}
	return $aConstantAndValue;
}

function getLangString($aLang,$aString)
{
	global $set_path;
	
	$sFileNameUser=$set_path . "/admin/config/language/" . $aLang . "_user.inc";
	$sFileNameSystem=$set_path . "/admin/language_src/" . $aLang . "_system.inc";
	
	$lArrayUser=getConstantAndValues($sFileNameUser);
	$lArraySystem=getConstantAndValues($sFileNameSystem);

	
	if ($lArrayUser["$aString"]!="")
		return $lArrayUser["$aString"];
	else 
		return $lArraySystem["$aString"];
	
	return -1;
}
function WA()
{
	if (!$_SESSION["admin_level"])
		return 0;
		
	if ($_SESSION["admin_level"]==9)
		return 0;
		
	return true;	
}
function getNumberOfDocumentsUploaded($aAdID)
{
	global $doc_tbl;
	$lSql="select count(f_id) as num from $doc_tbl where f_adid=$aAdID";
	$lRes=q($lSql);
	$lRow=mysql_fetch_array($lRes);
	return $lRow["num"];
}
function getNumberOfImagesUploaded($aAdID)
{
	global $pic_tbl;
	$lSql="select count(id) as num from $pic_tbl where pic_ad_id=$aAdID";
	$lRes=q($lSql);
	$lRow=mysql_fetch_array($lRes);
	return $lRow["num"];
}
/*
 * JMR: 06-11-09
 * */
function getNumberOfVideosUploaded($aAdID)
{
	global $vid_tbl;
	$lSql="select count(video_id) as num from $vid_tbl where video_adid=$aAdID";
	$lRes=q($lSql);
	$lRow=mysql_fetch_array($lRes);
	return $lRow["num"];
}

function PriceFormat($lPrice)
{
	global $set_amount_format;
	
	if ($set_amount_format=="EN")
		return number_format($lPrice);
	elseif ($set_amount_format=="NO" || $set_amount_format=="FR")
		return number_format($lPrice,2,","," ");
	else
	{
		$lSplitted=split(":",$set_amount_format);
		$lItem1=ereg_replace("BLANK"," ",$lSplitted[0]);
		$lItem2=ereg_replace("BLANK"," ",$lSplitted[1]);
		$lItem3=ereg_replace("BLANK"," ",$lSplitted[2]);
		return number_format($lPrice,"$lItem1","$lItem2","$lItem3");
	}
}
function getMySQLVersion()
{
	$lCharSetString="CHARACTER SET utf8 COLLATE utf8_unicode_ci";
	$lRes=q("SELECT VERSION() as mysql_version");
	$lRowVersion=mysql_fetch_array($lRes);
	$lMySQLVersion=$lRowVersion["mysql_version"];
	$lMySQLVersionArray=split("\.",$lMySQLVersion);
	
	foreach ($lMySQLVersionArray as $lItem)
	{
			$lNum=round($lItem);
			$lVerArray[]=$lNum;
	}
	return $lVerArray;
}
?>
